1 |
/*************************************************************************** |
2 |
* * |
3 |
* Copyright (C) 2007 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 |
mutex.Lock(); |
31 |
queue.push_back(pJob); |
32 |
mutex.Unlock(); |
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 |
while (!queue.empty()) { |
42 |
Runnable* pJob; |
43 |
|
44 |
// grab a new job from the queue |
45 |
mutex.Lock(); |
46 |
pJob = queue.front(); |
47 |
mutex.Unlock(); |
48 |
|
49 |
try { |
50 |
pJob->Run(); |
51 |
} catch (Exception e) { |
52 |
e.PrintMessage(); |
53 |
} catch (...) { |
54 |
std::cerr << "WorkerThread: an exception occured, could not finish the job"; |
55 |
std::cerr << std::endl << std::flush; |
56 |
} |
57 |
|
58 |
// remove processed job from the queue |
59 |
mutex.Lock(); |
60 |
queue.pop_front(); |
61 |
mutex.Unlock(); |
62 |
|
63 |
delete pJob; |
64 |
} |
65 |
|
66 |
// nothing left to do, sleep until new jobs arrive |
67 |
conditionJobsLeft.WaitIf(false); |
68 |
// reset flag |
69 |
conditionJobsLeft.Set(false); |
70 |
// unlock condition object so it can be turned again by other thread |
71 |
conditionJobsLeft.Unlock(); |
72 |
} |
73 |
} |
74 |
|
75 |
} // namespace LinuxSampler |