Synchronizing Threads

In this section, we'll take a look at the kind of problems conflicting threads can create. Say you have an integer variable named counter, and two threads are both trying to increment that variable. Each thread also has some other work to do (which we'll simulate by sprinkling a few Sleep statements in the code), so between the time thread1 reads counter and stores its value in a local variable, increments its value, and then assigns the new value back to counter, thread2 might have already done the same thing. This means that thread1 will wipe out thread2's work (conflicting access to a shared resource like this is called a race condition). Because both threads are sharing the same object, counter, they conflict. You can ...

Get Microsoft® Visual C#® .NET 2003 Kick Start now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.