]> git.stg.codes - stg.git/blob - projects/stargazer/eventloop.h
Readme for sgauth removed, CHANGES and TODO made empty
[stg.git] / projects / stargazer / eventloop.h
1 #ifndef __EVENT_LOOP_H__
2 #define __EVENT_LOOP_H__
3
4 #include <pthread.h>
5
6 #include "noncopyable.h"
7 #include "actions.h"
8
9 class EVENT_LOOP : private NONCOPYABLE,
10                    private ACTIONS_LIST
11 {
12     public:
13         bool Start();
14         bool Stop();
15         bool IsRunning() const { return _running; };
16
17         template <class ACTIVE_CLASS, typename DATA_TYPE>
18         void Enqueue(ACTIVE_CLASS & ac,
19                      typename ACTOR<ACTIVE_CLASS, DATA_TYPE>::TYPE a,
20                      DATA_TYPE d);
21
22     private:
23         bool _running;
24         bool _stopped;
25         pthread_t _tid;
26         pthread_mutex_t _mutex;
27         pthread_cond_t _condition;
28
29         EVENT_LOOP();
30         virtual ~EVENT_LOOP();
31
32         static void * Run(void *);
33         void Runner();
34
35         friend class EVENT_LOOP_SINGLETON;
36 };
37
38 class EVENT_LOOP_SINGLETON : private NONCOPYABLE
39 {
40     public:
41         static EVENT_LOOP & GetInstance();
42
43     private:
44         static EVENT_LOOP * _instance;
45         static void CreateInstance();
46
47         EVENT_LOOP_SINGLETON() {};
48         ~EVENT_LOOP_SINGLETON() {};
49 };
50
51 template <class ACTIVE_CLASS, typename DATA_TYPE>
52 void EVENT_LOOP::Enqueue(ACTIVE_CLASS & ac,
53                          typename ACTOR<ACTIVE_CLASS, DATA_TYPE>::TYPE a,
54                          DATA_TYPE d)
55 {
56 STG_LOCKER lock(&_mutex, __FILE__, __LINE__);
57 // Add new action
58 ACTIONS_LIST::Enqueue(ac, a, d);
59 // Signal about new action
60 pthread_cond_signal(&_condition);
61 }
62
63 #endif