1 // TaskManager.cpp
2
3 #include "TaskManager.h"
4
5 // #pragma mark -
6 // #pragma mark ----- Task -----
7
8 // constructor
Task(const char * name)9 Task::Task(const char* name)
10 : fName(name),
11 fThread(-1),
12 fTerminating(false),
13 fDone(true)
14 {
15 }
16
17 // destructor
~Task()18 Task::~Task()
19 {
20 }
21
22 // Run
23 status_t
Run()24 Task::Run()
25 {
26 const char* name = (fName.GetLength() > 0 ? fName.GetString() : "task");
27 #if USER
28 fThread = spawn_thread(&_ThreadEntry, name, B_NORMAL_PRIORITY, this);
29 #else
30 fThread = spawn_kernel_thread(&_ThreadEntry, name, B_NORMAL_PRIORITY, this);
31 #endif
32 if (fThread < 0)
33 return fThread;
34 fDone = false;
35 resume_thread(fThread);
36 return B_OK;
37 }
38
39 // Terminate
40 void
Terminate()41 Task::Terminate()
42 {
43 fTerminating = true;
44 Stop();
45 if (fThread >= 0) {
46 int32 result;
47 wait_for_thread(fThread, &result);
48 }
49 }
50
51 // IsDone
52 bool
IsDone() const53 Task::IsDone() const
54 {
55 return fDone;
56 }
57
58 // Stop();
59 void
Stop()60 Task::Stop()
61 {
62 }
63
64 // SetDone
65 void
SetDone(bool done)66 Task::SetDone(bool done)
67 {
68 fDone = 0;
69 }
70
71 // _ThreadEntry
72 int32
_ThreadEntry(void * data)73 Task::_ThreadEntry(void* data)
74 {
75 return ((Task*)data)->_Thread();
76 }
77
78 // _Thread
79 int32
_Thread()80 Task::_Thread()
81 {
82 Execute();
83 return 0;
84 }
85
86
87 // #pragma mark -
88 // #pragma mark ----- TaskManager -----
89
90 // constructor
TaskManager()91 TaskManager::TaskManager()
92 : fTasks()
93 {
94 }
95
96 // destructor
~TaskManager()97 TaskManager::~TaskManager()
98 {
99 TerminateAllTasks();
100 }
101
102 // RunTask
103 status_t
RunTask(Task * task)104 TaskManager::RunTask(Task* task)
105 {
106 if (!task)
107 return B_BAD_VALUE;
108 fTasks.Insert(task);
109 status_t error = task->Run();
110 if (error != B_OK) {
111 fTasks.Remove(task);
112 delete task;
113 }
114 return error;
115 }
116
117 // RemoveDoneTasks
118 void
RemoveDoneTasks()119 TaskManager::RemoveDoneTasks()
120 {
121 Task* task = fTasks.First();
122 while (task) {
123 Task* next = fTasks.GetNext(task);
124 if (task->IsDone()) {
125 fTasks.Remove(task);
126 task->Terminate();
127 delete task;
128 }
129 task = next;
130 }
131 }
132
133 // TerminateAllTasks
134 void
TerminateAllTasks()135 TaskManager::TerminateAllTasks()
136 {
137 while (Task* task = fTasks.First()) {
138 fTasks.Remove(task);
139 task->Terminate();
140 delete task;
141 }
142 }
143
144