C# Threading: a race condition example

前端 未结 4 959
孤街浪徒
孤街浪徒 2021-01-05 11:22

I am reading http://www.mono-project.com/ThreadsBeginnersGuide.

The first example looks like this:

public class FirstUnsyncThreads {
    private int          


        
4条回答
  •  死守一世寂寞
    2021-01-05 11:56

    The increments are not happening out of order, the Console.WriteLine(...) is writing the output from multiple threads into a single-threaded console, and the synchronization from many threads to one thread is causing the messages to appear out of order.

    I assume this example attempted to create a race condition, and in your case failed. Unfortunately, concurrency issues, such as a race condition and deadlocks, are hard to predict and reproduce due to their nature. You might want to try and run it a few more times, alter it to use more threads and each thread should increment more times (say 100,000). Then you might see that the end result will not equal the sum of all the increments (caused by a race condition).

提交回复
热议问题