Colobot
worker_thread.h
1 /*
2  * This file is part of the Colobot: Gold Edition source code
3  * Copyright (C) 2001-2016, Daniel Roux, EPSITEC SA & TerranovaTeam
4  * http://epsitec.ch; http://colobot.info; http://github.com/colobot
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14  * See the GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see http://gnu.org/licenses
18  */
19 
20 #pragma once
21 
22 #include "common/make_unique.h"
23 
24 #include "common/thread/sdl_cond_wrapper.h"
25 #include "common/thread/sdl_mutex_wrapper.h"
26 #include "common/thread/thread.h"
27 
28 #include <functional>
29 #include <string>
30 #include <queue>
31 
37 {
38 public:
39  using ThreadFunctionPtr = std::function<void()>;
40 
41 public:
42  CWorkerThread(std::string name = "")
43  : m_thread(std::bind(&CWorkerThread::Run, this), name)
44  {
45  m_thread.Start();
46  }
47 
48  ~CWorkerThread()
49  {
50  m_mutex.Lock();
51  m_running = false;
52  m_cond.Signal();
53  m_mutex.Unlock();
54  m_thread.Join();
55  }
56 
57  void Start(ThreadFunctionPtr func)
58  {
59  m_mutex.Lock();
60  m_queue.push(func);
61  m_cond.Signal();
62  m_mutex.Unlock();
63  }
64 
65  CWorkerThread(const CWorkerThread&) = delete;
66  CWorkerThread& operator=(const CWorkerThread&) = delete;
67 
68 private:
69  void Run()
70  {
71  m_mutex.Lock();
72  while (true)
73  {
74  while (m_queue.empty() && m_running)
75  {
76  m_cond.Wait(*m_mutex);
77  }
78  if (!m_running) break;
79 
80  ThreadFunctionPtr func = m_queue.front();
81  m_queue.pop();
82  func();
83  }
84  m_mutex.Unlock();
85  }
86 
87  CThread m_thread;
88  CSDLMutexWrapper m_mutex;
89  CSDLCondWrapper m_cond;
90  bool m_running = true;
91  std::queue<ThreadFunctionPtr> m_queue;
92 };
Wrapper for safe creation/deletion of SDL_cond.
Definition: sdl_cond_wrapper.h:30
Wrapper for safe creation/deletion of SDL_mutex.
Definition: sdl_mutex_wrapper.h:28
Wrapper for using SDL_thread with std::function.
Definition: thread.h:34
Thread that runs functions, one at a time.
Definition: worker_thread.h:36