Search code examples
multithreadingcritical-region

Many threads and critical region


If I have many threads running at the same time how can I allow only 1 thread to enter the critical region? Also what will happen if I had more than 1 thread in the critical region?


Solution

  • There are several kinds of bugs that can happen as a result of improperly-protected critical sections, but the most common is called a race condition. This occurs when the correctness of your program's behavior or output is dependent on events occurring in a particular sequence, but it's possible that the events will occur in a different sequence. This will tend to cause the program to behave in an unexpected or unpredictable manner. (Sorry to be a little vague on that last point but by its very nature it's often difficult to predict in advance what the exact result will be other than to say "it probably won't be what you wanted").

    Generally, to fix this, you'd use some kind of lock to ensure that only one thread can access the critical section at once. The most common mechanism for this is a mutex lock, which is used for the "simple" case - you have some kind of a shared resource and only one thread can access it at one time.

    There are some other mechanisms available too for more complicated cases, such as:

    • Reader-Writer Locks - either one person can write to the resource or an unlimited number of people can be reading from it.
    • Counting semaphore - some specified number of threads can access a particular thread at one time. As an analogy, think of a parking lot that only has, for example, 100 spaces - once 100 cars are parked there, they can't accept any more (or, at least, until one of them leaves).
    • The .NET Framework provides a ManualResetEvent - basically, the threads in question have to wait until an event happens.
    • This isn't a lock per se, but it's becoming increasingly common to use immutable data structures to obviate the need for locking in the first place. The idea here is that no thread can modify another thread's data, they're always working against either a local version or the unmodified "central" version.