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.

If methods A and B ran concurrently on different threads, might it be possible for B<br />

to write “0”? The answer is yes—for the following reasons:<br />

• The compiler, CLR, or CPU may reorder your program’s instructions to improve<br />

efficiency.<br />

• The compiler, CLR, or CPU may introduce caching optimizations such that<br />

assignments to variables won’t be visible to other threads right away.<br />

C# and the runtime are very careful to ensure that such optimizations don’t break<br />

ordinary single-threaded code—or multithreaded code that makes proper use of<br />

locks. Outside of these scenarios, you must explicitly defeat these optimizations by<br />

creating memory barriers (also called memory fences) to limit the effects of instruction<br />

reordering and read/write caching.<br />

Full fences<br />

The simplest kind of memory barrier is a full memory barrier (full fence), which<br />

prevents any kind of instruction reordering or caching around that fence. Calling<br />

Thread.MemoryBarrier generates a full fence; we can fix our example by applying four<br />

full fences as follows:<br />

class Foo<br />

{<br />

int _answer;<br />

bool _complete;<br />

void A()<br />

{<br />

_answer = 123;<br />

Thread.MemoryBarrier(); // Barrier 1<br />

_complete = true;<br />

Thread.MemoryBarrier(); // Barrier 2<br />

}<br />

void B()<br />

{<br />

Thread.MemoryBarrier(); // Barrier 3<br />

if (_complete)<br />

{<br />

Thread.MemoryBarrier(); // Barrier 4<br />

Console.WriteLine (_answer);<br />

}<br />

}<br />

}<br />

Barriers 1 and 4 prevent this example from writing “0”. Barriers 2 and 3 provide a<br />

freshness guarantee: they ensure that if B ran after A, reading _complete would evaluate<br />

to true.<br />

A full fence takes a few tens of nanoseconds.<br />

826 | Chapter 21: Threading

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

Saved successfully!

Ooh no, something went wrong!