15.01.2013 Views

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

Free-ebooks-library - Bahar Ali Khan

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.

Fortunately, the pool manager has a backup plan. If its queue remains stationary<br />

for more than half a second, it responds by creating more threads—one every halfsecond—up<br />

to the capacity of the thread pool.<br />

The half-second delay is a two-edged sword. On the one hand, it means that a<br />

one-off burst of brief activity doesn’t make a program suddenly consume an extra<br />

unnecessary 40 MB (or more) of memory. On the other hand, it can needlessly<br />

delay things when a pooled thread blocks, such as when querying a database or<br />

calling WebClient.DownloadFile. For this reason, you can tell the pool manager not<br />

to delay in the allocation of the first x threads, by calling SetMinThreads, for<br />

instance:<br />

ThreadPool.SetMinThreads (50, 50);<br />

(The second value indicates how many threads to assign to I/O completion ports,<br />

which are used by the APM, described in Chapter 23.)<br />

The default value is one thread per core.<br />

Blocking<br />

A thread is deemed blocked when its execution is paused for some reason, such as<br />

when Sleeping or waiting for another to end via Join or EndInvoke. A blocked thread<br />

immediately yields its processor time slice, and from then on consumes no processor<br />

time until its blocking condition is satisfied. You can test for a thread being blocked<br />

via its ThreadState property:<br />

bool blocked = (someThread.ThreadState & ThreadState.WaitSleepJoin) != 0;<br />

ThreadState is a flags enum, combining three “layers” of data in<br />

a bitwise fashion. Most values, however, are redundant, unused,<br />

or deprecated. The following code strips a ThreadState to<br />

one of four useful values: Unstarted, Running, WaitSleepJoin,<br />

and Stopped:<br />

public static ThreadState SimpleThreadState (ThreadState ts)<br />

{<br />

return ts & (ThreadState.Unstarted |<br />

ThreadState.WaitSleepJoin |<br />

ThreadState.Stopped);<br />

}<br />

The ThreadState property is useful for diagnostic purposes, but<br />

unsuitable for synchronization, because a thread’s state may<br />

change in between testing ThreadState and acting on that<br />

information.<br />

When a thread blocks or unblocks, the operating system performs a context<br />

switch. This incurs an overhead of a few microseconds.<br />

Synchronization | 807<br />

Threading

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

Saved successfully!

Ooh no, something went wrong!