2015-11-07 09:00:25 +01:00
# pragma once
# ifndef MESSMER_CPPUTILS_THREAD_THREADSYSTEM_H
# define MESSMER_CPPUTILS_THREAD_THREADSYSTEM_H
# include "../macros.h"
# include <boost/thread.hpp>
# include <list>
# include <functional>
namespace cpputils {
//TODO Test
class ThreadSystem final {
private :
struct RunningThread {
2015-11-12 22:07:20 +01:00
std : : function < bool ( ) > loopIteration ; // The loopIteration callback returns true, if more iterations should be run, and false, if the thread should be terminated.
2015-11-07 09:00:25 +01:00
boost : : thread thread ; // boost::thread because we need it to be interruptible.
} ;
public :
using Handle = std : : list < RunningThread > : : iterator ;
static ThreadSystem & singleton ( ) ;
2015-11-12 22:07:20 +01:00
Handle start ( std : : function < bool ( ) > loopIteration ) ;
2015-11-07 09:00:25 +01:00
void stop ( Handle handle ) ;
private :
ThreadSystem ( ) ;
2015-11-12 22:07:20 +01:00
static void _runThread ( std : : function < bool ( ) > loopIteration ) ;
2015-11-07 09:00:25 +01:00
static void _onBeforeFork ( ) ;
static void _onAfterFork ( ) ;
2015-11-07 09:11:12 +01:00
//TODO Rename to _doOnBeforeFork and _doAfterFork or similar, because they also handle locking _mutex for fork().
2015-11-07 09:00:25 +01:00
void _stopAllThreadsForRestart ( ) ;
void _restartAllThreads ( ) ;
2015-11-12 22:07:20 +01:00
boost : : thread _startThread ( std : : function < bool ( ) > loopIteration ) ;
2015-11-07 09:00:25 +01:00
std : : list < RunningThread > _runningThreads ; // std::list, because we give out iterators as handles
2015-11-07 09:11:12 +01:00
boost : : mutex _mutex ;
2015-11-07 09:00:25 +01:00
DISALLOW_COPY_AND_ASSIGN ( ThreadSystem ) ;
} ;
}
# endif