2 * Copyright (c) 2005, Eric Crahen
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is furnished
9 * to do so, subject to the following conditions:
11 * The above copyright notice and this permission notice shall be included in all
12 * copies or substantial portions of the Software.
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
18 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
19 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 #include "DeferredInterruptionScope.h"
25 #include "ThreadImpl.h"
26 #include "ThreadQueue.h"
33 ThreadQueue::ThreadQueue()
36 ZTDEBUG("ThreadQueue created\n");
40 ThreadQueue::~ThreadQueue() {
42 ZTDEBUG("ThreadQueue waiting on remaining threads...\n");
44 // Ensure the current thread is mapped.
45 ThreadImpl
* impl
= ThreadImpl::current();
47 bool threadsWaiting
= false;
48 bool waitRequired
= false;
52 TaskList shutdownTasks
;
54 { // Check the queue to for pending user threads
56 Guard
<FastLock
> g(_lock
);
58 waitRequired
= (_waiter
!= (ThreadImpl
*)1);
61 threadsWaiting
= !_userThreads
.empty() || !_pendingThreads
.empty();
63 //ZTDEBUG("Wait required: %d\n", waitRequired);
64 //ZTDEBUG("Threads waiting: %d\n", threadsWaiting);
66 // Auto-cancel any active threads at the time main() goes out of scope
67 // "force" a gentle exit from the executing tasks; eventually the user-
68 // threads will transition into pending-threads
71 // Remove all the tasks about to be run from the task list so an indication
72 // can be given to threads calling removeShutdownTask() too late.
73 std::remove_copy(_shutdownTasks
.begin(),
75 std::back_inserter(shutdownTasks
),
78 //ZTDEBUG("Threads waiting: %d\n", threadsWaiting);
82 // Execute the shutdown tasks
83 for(TaskList::iterator i
= shutdownTasks
.begin(); i
!= shutdownTasks
.end(); ++i
) {
91 // Wait for all the users threads to get into the appropriate state
95 Monitor
& m
= _waiter
->getMonitor();
97 // Defer interruption while this thread waits for a signal from
98 // the last pending user thread
99 Guard
<Monitor
, CompoundScope
<DeferredInterruptionScope
, LockedScope
> > g(m
);
100 //ZTDEBUG("Threads waiting: %d %d\n", _userThreads.size(), _pendingThreads.size());
102 // Avoid race-condition where the last threads are done with thier tasks, but
103 // only begin the final part of the clean up phase after this destructor begins
104 // to run. Takes advantage of the fact that if all remaining threads have transitioned
105 // into a pending state by the time execution reaches this point, then there is no
107 waitRequired
= waitRequired
&& !(_userThreads
.empty() && !_pendingThreads
.empty());
109 // Reference threads can't be interrupted or otherwise
110 // manipulated. The only signal this monitor will receive
111 // at this point will be from the last pending thread.
112 if(waitRequired
&& m
.wait() != Monitor::SIGNALED
) {
116 // Join those pending threads
117 pollPendingThreads();
121 // Clean up the reference threads
122 pollReferenceThreads();
124 ZTDEBUG("ThreadQueue destroyed\n");
129 void ThreadQueue::insertPendingThread(ThreadImpl
* impl
) {
130 ZTDEBUG("insertPendingThread()\n");
131 Guard
<FastLock
> g(_lock
);
133 // Move from the user-thread list to the pending-thread list
134 ThreadList::iterator i
= std::find(_userThreads
.begin(), _userThreads
.end(), impl
);
135 if(i
!= _userThreads
.end())
136 _userThreads
.erase(i
);
138 _pendingThreads
.push_back(impl
);
140 // Wake the main thread,if its waiting, when the last pending-thread becomes available;
141 // Otherwise, take note that no wait for pending threads to finish is needed
142 if(_userThreads
.empty())
143 if(_waiter
&& _waiter
!= (ThreadImpl
*)1)
144 _waiter
->getMonitor().notify();
146 _waiter
= (ThreadImpl
*)!_waiter
;
148 ZTDEBUG("1 pending-thread added.\n");
152 void ThreadQueue::insertReferenceThread(ThreadImpl
* impl
) {
154 Guard
<FastLock
> g(_lock
);
155 _referenceThreads
.push_back(impl
);
157 ZTDEBUG("1 reference-thread added.\n");
161 void ThreadQueue::insertUserThread(ThreadImpl
* impl
) {
163 Guard
<FastLock
> g(_lock
);
164 _userThreads
.push_back(impl
);
166 // Reclaim pending-threads
167 pollPendingThreads();
169 // Auto-cancel threads that are started when main() is out of scope
173 ZTDEBUG("1 user-thread added.\n");
178 void ThreadQueue::pollPendingThreads() {
180 ZTDEBUG("pollPendingThreads()\n");
182 for(ThreadList::iterator i
= _pendingThreads
.begin(); i
!= _pendingThreads
.end();) {
184 ThreadImpl
* impl
= (ThreadImpl
*)*i
;
185 ThreadOps::join(impl
);
187 impl
->delReference();
189 i
= _pendingThreads
.erase(i
);
191 ZTDEBUG("1 pending-thread reclaimed.\n");
197 void ThreadQueue::pollReferenceThreads() {
199 ZTDEBUG("pollReferenceThreads()\n");
201 for(ThreadList::iterator i
= _referenceThreads
.begin(); i
!= _referenceThreads
.end(); ++i
) {
203 ThreadImpl
* impl
= (ThreadImpl
*)*i
;
204 impl
->delReference();
206 ZTDEBUG("1 reference-thread reclaimed.\n");
212 void ThreadQueue::pollUserThreads() {
214 ZTDEBUG("pollUserThreads()\n");
216 for(ThreadList::iterator i
= _userThreads
.begin(); i
!= _userThreads
.end(); ++i
) {
218 ThreadImpl
* impl
= *i
;
221 ZTDEBUG("1 user-thread reclaimed.\n");
227 void ThreadQueue::insertShutdownTask(Task
& task
) {
229 bool hasWaiter
= false;
233 Guard
<FastLock
> g(_lock
);
235 // Execute later when the ThreadQueue is destroyed
236 if( !(hasWaiter
= (_waiter
!= 0)) ) {
238 _shutdownTasks
.push_back(task
);
239 //ZTDEBUG("1 shutdown task added. %d\n", _shutdownTasks.size());
245 // Execute immediately if things are shutting down
251 bool ThreadQueue::removeShutdownTask(const Task
& task
) {
253 Guard
<FastLock
> g(_lock
);
255 TaskList::iterator i
= std::find(_shutdownTasks
.begin(), _shutdownTasks
.end(), task
);
256 bool removed
= (i
!= _shutdownTasks
.end());
258 _shutdownTasks
.erase(i
);
260 //ZTDEBUG("1 shutdown task removed (%d)-%d\n", removed, _shutdownTasks.size());