]> git.stg.codes - stg.git/blob - projects/stargazer/actions.h
Добавление исходников
[stg.git] / projects / 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     ACTIVE_CLASS & activeClass;
48     typename ACTOR<ACTIVE_CLASS, DATA_TYPE>::TYPE actor;
49     DATA_TYPE data;
50 };
51
52 // A list of an actions
53 // All methods are thread-safe
54 class ACTIONS_LIST : private std::list<BASE_ACTION *>
55 {
56 public:
57     // Just a typedef for parent class
58     typedef std::list<BASE_ACTION *> parent;
59
60     // Initialize mutex
61     ACTIONS_LIST();
62     // Delete actions and destroy mutex
63     ~ACTIONS_LIST();
64
65     parent::iterator begin();
66     parent::iterator end();
67     parent::const_iterator begin() const;
68     parent::const_iterator end() const;
69
70     bool empty() const;
71     size_t size() const;
72     void swap(ACTIONS_LIST & list);
73
74     // Add an action to list
75     template <class ACTIVE_CLASS, typename DATA_TYPE>
76     void Enqueue(ACTIVE_CLASS & ac,
77                  typename ACTOR<ACTIVE_CLASS, DATA_TYPE>::TYPE a,
78                  DATA_TYPE d);
79     // Invoke all actions in the list
80     void InvokeAll();
81 private:
82     mutable pthread_mutex_t mutex;
83 };
84
85 #include "actions.inl.h"
86
87 #endif