1 |
/*************************************************************************** |
2 |
* * |
3 |
* Copyright (C) 2007 - 2013 Christian Schoenebeck, Grigor Iliev * |
4 |
* * |
5 |
* This program is free software; you can redistribute it and/or modify * |
6 |
* it under the terms of the GNU General Public License as published by * |
7 |
* the Free Software Foundation; either version 2 of the License, or * |
8 |
* (at your option) any later version. * |
9 |
* * |
10 |
* This program is distributed in the hope that it will be useful, * |
11 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of * |
12 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * |
13 |
* GNU General Public License for more details. * |
14 |
* * |
15 |
* You should have received a copy of the GNU General Public License * |
16 |
* along with this program; if not, write to the Free Software * |
17 |
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * |
18 |
* MA 02110-1301 USA * |
19 |
***************************************************************************/ |
20 |
|
21 |
#include "WorkerThread.h" |
22 |
|
23 |
#include "Exception.h" |
24 |
|
25 |
namespace LinuxSampler { |
26 |
|
27 |
WorkerThread::WorkerThread() : Thread(true, false, 0, -4) { } |
28 |
|
29 |
void WorkerThread::Execute(Runnable* pJob) { |
30 |
{ |
31 |
LockGuard lock(mutex); |
32 |
queue.push_back(pJob); |
33 |
} |
34 |
StartThread(); // ensure thread is running |
35 |
conditionJobsLeft.Set(true); // wake up thread |
36 |
} |
37 |
|
38 |
// Entry point for the worker thread. |
39 |
int WorkerThread::Main() { |
40 |
while (true) { |
41 |
|
42 |
#if CONFIG_PTHREAD_TESTCANCEL |
43 |
TestCancel(); |
44 |
#endif |
45 |
while (true) { |
46 |
Runnable* pJob; |
47 |
|
48 |
// grab a new job from the queue |
49 |
{ |
50 |
LockGuard lock(mutex); |
51 |
if (queue.empty()) break; |
52 |
|
53 |
pJob = queue.front(); |
54 |
queue.pop_front(); |
55 |
} |
56 |
|
57 |
try { |
58 |
pJob->Run(); |
59 |
} catch (Exception e) { |
60 |
e.PrintMessage(); |
61 |
} catch (...) { |
62 |
std::cerr << "WorkerThread: an exception occured, could not finish the job"; |
63 |
std::cerr << std::endl << std::flush; |
64 |
} |
65 |
|
66 |
delete pJob; |
67 |
} |
68 |
|
69 |
// nothing left to do, sleep until new jobs arrive |
70 |
conditionJobsLeft.WaitIf(false); |
71 |
// reset flag |
72 |
conditionJobsLeft.Set(false); |
73 |
// unlock condition object so it can be turned again by other thread |
74 |
conditionJobsLeft.Unlock(); |
75 |
} |
76 |
return 0; |
77 |
} |
78 |
|
79 |
} // namespace LinuxSampler |