21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

#ifndef WIN32<br />

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

#else<br />

static DWORD WINAPI worker_thread(LPVOID arg) {<br />

#endif<br />

int done = 0;<br />

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

spc_threadpool_task *task;<br />

while (!done) {<br />

SPC_ACQUIRE_MUTEX(threadpool_mutex);<br />

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

cleanup_worker(arg);<br />

return 0;<br />

}<br />

SPC_CLEANUP_PUSH(cleanup_worker, arg);<br />

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

if (!pool->tasks) SPC_WAIT_COND(pool->cond, threadpool_mutex);<br />

if ((task = pool->tasks) != 0)<br />

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

} else done = 1;<br />

SPC_CLEANUP_POP(1);<br />

if (!done && task) {<br />

task->fnptr(task->arg);<br />

free(task);<br />

}<br />

}<br />

return 0;<br />

}<br />

Before any tasks can be scheduled, the pool of threads to run them needs to be created.<br />

This is done by making a call to spc_threadpool_init( ) and specifying the<br />

number of threads that will be in the pool. Be careful not to make the size of the pool<br />

too small. It is better for it to be too big than not big enough. Ideally, you would like<br />

to have scheduled tasks remain scheduled for as short a time as possible. Finding the<br />

right size for the thread pool will likely take some tuning, and it is probably a good<br />

idea to make it a configurable option in your program.<br />

If there is a problem creating any of the threads to be part of the pool, any already<br />

created threads are canceled, and the initialization function will return failure. Successive<br />

attempts can be made to initialize the pool without any leakage of resources.<br />

spc_threadpool_t *spc_threadpool_init(int pool_size) {<br />

int i;<br />

spc_threadpool_t *pool;<br />

#ifdef WIN32<br />

if (!threadpool_mutex) threadpool_mutex = CreateMutex(NULL, FALSE, 0);<br />

#endif<br />

if (!(pool = (spc_threadpool_t *)malloc(sizeof(spc_threadpool_t))))<br />

return 0;<br />

722 | Chapter 13: Other Topics<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!