]> git.stg.codes - stg.git/blob - stargazer/actions.h
Port to CMake, get rid of os_int.h.
[stg.git] / stargazer / actions.h
1 #ifndef __ACTIONS_H__
2 #define __ACTIONS_H__
3
4 // Usage:
5 //
6 // ACTIONS_LIST actionsList;
7 // CLASS myClass;
8 // DATA1 myData1;
9 // DATA2 myData2;
10 //
11 // actionsList.Enqueue(myClass, &CLASS::myMethod1, myData1);
12 // actionsList.Enqueue(myClass, &CLASS::myMethod2, myData2);
13 //
14 // actionsList.InvokeAll();
15
16 #include <pthread.h>
17 #include <list>
18 #include <functional>
19
20 // Generalized actor type - a method of some class with one argument
21 template <class ACTIVE_CLASS, typename DATA_TYPE>
22 struct ACTOR
23 {
24 typedef void (ACTIVE_CLASS::*TYPE)(DATA_TYPE);
25 };
26
27 // Abstract base action class for polymorphic action invocation
28 class BASE_ACTION
29 {
30 public:
31     virtual ~BASE_ACTION() {}
32     virtual void Invoke() = 0;
33 };
34
35 // Concrete generalized action type - an actor with it's data and owner
36 template <class ACTIVE_CLASS, typename DATA_TYPE>
37 class ACTION : public BASE_ACTION,
38                public std::unary_function<ACTIVE_CLASS &, void>
39 {
40 public:
41     ACTION(ACTIVE_CLASS & ac,
42            typename ACTOR<ACTIVE_CLASS, DATA_TYPE>::TYPE a,
43            DATA_TYPE d)
44         : activeClass(ac), actor(a), data(d) {}
45     void Invoke();
46 private:
47     ACTION(const ACTION<ACTIVE_CLASS, DATA_TYPE> & rvalue);
48     ACTION<ACTIVE_CLASS, DATA_TYPE> & operator=(const ACTION<ACTIVE_CLASS, DATA_TYPE> & rvalue);
49
50     ACTIVE_CLASS & activeClass;
51     typename ACTOR<ACTIVE_CLASS, DATA_TYPE>::TYPE actor;
52     DATA_TYPE data;
53 };
54
55 // A list of an actions
56 // All methods are thread-safe
57 class ACTIONS_LIST : private std::list<BASE_ACTION *>
58 {
59 public:
60     // Just a typedef for parent class
61     typedef std::list<BASE_ACTION *> parent;
62
63     // Initialize mutex
64     ACTIONS_LIST();
65     // Delete actions and destroy mutex
66     virtual ~ACTIONS_LIST();
67
68     parent::iterator begin();
69     parent::iterator end();
70     parent::const_iterator begin() const;
71     parent::const_iterator end() const;
72
73     bool empty() const;
74     size_t size() const;
75     void swap(ACTIONS_LIST & list);
76
77     // Add an action to list
78     template <class ACTIVE_CLASS, typename DATA_TYPE>
79     void Enqueue(ACTIVE_CLASS & ac,
80                  typename ACTOR<ACTIVE_CLASS, DATA_TYPE>::TYPE a,
81                  DATA_TYPE d);
82     // Invoke all actions in the list
83     void InvokeAll();
84 private:
85     mutable pthread_mutex_t mutex;
86 };
87
88 #include "actions.inl.h"
89
90 #endif