21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

handles[0] = cond;<br />

handles[1] = mutex;<br />

ResetEvent(cond);<br />

ReleaseMutex(mutex);<br />

WaitForMultipleObjectsEx(2, handles, TRUE, INFINITE, FALSE);<br />

}<br />

#endif<br />

int spc_threadpool_schedule(spc_threadpool_t *pool, spc_threadpool_fnptr fnptr,<br />

void *arg) {<br />

spc_threadpool_task *task;<br />

SPC_ACQUIRE_MUTEX(threadpool_mutex);<br />

if (!pool->tids) {<br />

SPC_RELEASE_MUTEX(threadpool_mutex);<br />

return 0;<br />

}<br />

if (!(task = (spc_threadpool_task *)malloc(sizeof(spc_threadpool_task)))) {<br />

SPC_RELEASE_MUTEX(threadpool_mutex);<br />

return 0;<br />

}<br />

task->fnptr = fnptr;<br />

task->arg = arg;<br />

task->next = 0;<br />

if (pool->tail) pool->tail->next = task;<br />

else pool->tasks = task;<br />

pool->tail = task;<br />

SPC_SIGNAL_COND(pool->cond);<br />

SPC_RELEASE_MUTEX(threadpool_mutex);<br />

return 1;<br />

}<br />

Each pooled thread will normally run in a loop that waits for new tasks to be scheduled.<br />

When a new task is scheduled, it will be removed from the list of scheduled<br />

tasks and run. When there are no scheduled tasks, the threads will be put to sleep,<br />

waiting on the condition that spc_threadpool_schedule( ) will signal when a new task<br />

is scheduled. Note that pthread_cond_wait( ) is a cancellation point. If the thread is<br />

cancelled while it is waiting for the condition to be signaled, the guard mutex will be<br />

locked. As a result, we need to push a cleanup handler to undo that so that other<br />

threads will successfully die when they are cancelled as well. (The importance of this<br />

behavior will become apparent shortly.)<br />

static void cleanup_worker(void *arg) {<br />

spc_threadpool_t *pool = (spc_threadpool_t *)arg;<br />

if (pool->destroy && !--pool->destroy) {<br />

SPC_DESTROY_COND(pool->cond);<br />

free(pool);<br />

}<br />

SPC_RELEASE_MUTEX(threadpool_mutex);<br />

}<br />

Guarding Against Spawning Too Many Threads | 721<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!