Branch data Line data Source code
1 : : // $Id: Continuation.h 2698 2006-04-03 05:50:52Z vern $
2 : : //
3 : : // Helper class to implement continuation-like mechanisms for
4 : : // suspending/resuming tasks for incremental operation.
5 : : //
6 : : // TODO: - Document how to use this.
7 : : // - Find some nice macro-based interface?
8 : :
9 : : #ifndef continuation_h
10 : : #define continuation_h
11 : :
12 : : #include "List.h"
13 : :
14 : 3 : class Continuation {
15 : : public:
16 : 3 : Continuation() { current_level = 0; suspend_level = -1; }
17 : :
18 : : // Returns true if we're called for the first time.
19 : 113 : bool NewInstance() const
20 : 113 : { return suspend_level < current_level; }
21 : :
22 : : // Returns true if a function called by us has suspended itself.
23 : 214 : bool ChildSuspended() const
24 : 214 : { return suspend_level > current_level; }
25 : :
26 : : // Returns true if we have suspended before and are now called again to
27 : : // resume our operation.
28 : 0 : bool Resuming() const
29 : 0 : { return suspend_level == current_level; }
30 : :
31 : : // To be called just before we suspend operation for the time being.
32 : 0 : void Suspend()
33 : 0 : { suspend_level = current_level; }
34 : :
35 : : // To be called right after we resumed operation.
36 : 0 : void Resume()
37 : 0 : { suspend_level = -1; }
38 : :
39 : : // If we call a function which may suspend itself, we need to
40 : : // enclose the call with calls to SaveContext() and RestoreContext().
41 : 140 : void SaveContext() { ++current_level; }
42 : 140 : void RestoreContext() { --current_level; }
43 : :
44 : : // We can store some user state which can be retrieved later.
45 : 4 : void SaveState(void* user_ptr)
46 : 4 : { states.replace(current_level, user_ptr); }
47 : :
48 : 0 : void* RestoreState() const
49 : 0 : { return states[current_level]; }
50 : :
51 : : private:
52 : : int current_level;
53 : : int suspend_level;
54 : :
55 : 10 : declare(PList, void);
56 : : typedef PList(void) voidp_list;
57 : :
58 : : voidp_list states;
59 : : };
60 : :
61 : : #endif
|