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 />

pool->tids = (pthread_t *)malloc(sizeof(pthread_t) * pool_size);<br />

#else<br />

pool->tids = (HANDLE *)malloc(sizeof(HANDLE) * pool_size);<br />

#endif<br />

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

free(pool);<br />

return 0;<br />

}<br />

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

pool->size = pool_size;<br />

pool->destroy = 0;<br />

pool->tasks = 0;<br />

pool->tail = 0;<br />

SPC_ACQUIRE_MUTEX(threadpool_mutex);<br />

for (i = 0; i < pool->size; i++) {<br />

if (!SPC_CREATE_THREAD(pool->tids[i], worker_thread, pool)) {<br />

pool->destroy = i;<br />

free(pool->tids);<br />

pool->tids = 0;<br />

SPC_RELEASE_MUTEX(threadpool_mutex);<br />

return 0;<br />

}<br />

}<br />

SPC_RELEASE_MUTEX(threadpool_mutex);<br />

return pool;<br />

}<br />

Finally, when the thread pool is no longer needed, it can be cleaned up by calling<br />

spc_threadpool_cleanup( ). All of the threads in the pool will be cancelled, and any<br />

scheduled tasks will be destroyed without being run.<br />

void spc_threadpool_cleanup(spc_threadpool_t *pool) {<br />

spc_threadpool_task *next;<br />

SPC_ACQUIRE_MUTEX(threadpool_mutex);<br />

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

while (pool->tasks) {<br />

next = pool->tasks->next;<br />

free(pool->tasks);<br />

pool->tasks = next;<br />

}<br />

free(pool->tids);<br />

pool->tids = 0;<br />

}<br />

pool->destroy = pool->size;<br />

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

SPC_RELEASE_MUTEX(threadpool_mutex);<br />

}<br />

Guarding Against Spawning Too Many Threads | 723<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!