C# Threading: a race condition example

前端 未结 4 964
孤街浪徒
孤街浪徒 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:51

    Synchronization is essential when multiple threads are present. In this case you are seeing that both threads read and write to this.i , but no good attempt is done at synchronize these accesses. Since both of them concurrently modify the same memory area, you observe the jumbled output. The call to Sleep is dangerous, it is an approach which leads to sure bugs. You cannot assume that the threads will be always displaced by the inital 10 ms.

    In short: Never use Sleep for synchronization :-) but instead adopt some kind of thread synchronization technique (eg. locks, mutexes, semaphores). Always try to use the lightest possible lock that will fulfill your need....

    A useful resource is the book by Joe Duffy, Concurrent Programming on Windows.

提交回复
热议问题