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.

The proper way to handle a program using an arbitrary number of threads is to generate<br />

a “pool” of threads in advance, which solves two problems. First, it removes<br />

the thread creation time, which can be expensive because of the cost of accepting a<br />

new connection. Second, it prevents system resources from being exhausted because<br />

too many threads have been spawned.<br />

We can effectively map threads that would otherwise be spawned to tasks. Normally<br />

when a thread is spawned, a function to serve as its entry point is specified along<br />

with a pointer to void as an argument that can be any application-specific data to be<br />

passed to the thread’s entry point. We’ll mirror these semantics in our tasks and create<br />

a function, spc_threadpool_schedule( ) to schedule a new task. The task will be<br />

stored at the end of a list so that tasks will be run in the order they are scheduled.<br />

When a new task is scheduled, the system will signal a condition object, which<br />

pooled threads will wait on when they have no tasks to run. Figure 13-1 illustrates<br />

the sequence of events that occurs in each pooled thread.<br />

Notice that the number of tasks that can be scheduled is not restricted. As long as<br />

there is sufficient memory to create a new task structure, tasks will be scheduled.<br />

Depending on how the thread pool is to be used, it may be desirable to limit the<br />

number of tasks that can be scheduled at any one time. For example, in a network<br />

server that schedules each connection as a task, you may want to immediately limit<br />

the number of connections until all of the already scheduled connections have been<br />

run.<br />

#include <br />

#ifndef WIN32<br />

#include <br />

#else<br />

#include <br />

#endif<br />

Task in<br />

queue?<br />

Figure 13-1. Actions carried out by pooled threads<br />

typedef void (*spc_threadpool_fnptr)(void *);<br />

NO<br />

Wait for<br />

task<br />

YES<br />

Run queued<br />

task<br />

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