C# Threading: a race condition example

前端 未结 4 960
孤街浪徒
孤街浪徒 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 12:04

    I think the writer of the article has confused things.

    VoteyDisciple is correct that ++i is not atomic and a race condition can occur if the target is not locked during the operation but this will not cause the issue described above.

    If a race condition occurs calling ++i then internal operations of the ++ operator will look something like:-

    1. 1st thread reads value 0
    2. 2nd thread reads value 0
    3. 1st thread increments value to 1
    4. 2nd thread increments value to 1
    5. 1st thread writes value 1
    6. 2nd thread writes value 1

    The order of operations 3 to 6 is unimportant, the point is that both the read operations, 1 and 2, can occur when the variable has value x resulting in the same incrementation to y, rather than each thread performing incrementations for distinct values of x and y.

    This may result in the following output:-

    First runner incrementing i from 0 to 1
    Second runner incrementing i from 0 to 1
    

    What would be even worse is the following:-

    1. 1st thread reads value 0
    2. 2nd thread reads value 0
    3. 2nd thread increments value to 1
    4. 2nd thread writes value 1
    5. 2nd thread reads value 1
    6. 2nd thread increments value to 2
    7. 2nd thread writes value 2
    8. 1st thread increments value to 1
    9. 1st thread writes value 1
    10. 2nd thread reads value 1
    11. 2nd thread increments value to 2
    12. 2nd thread writes value 2

    This may result in the following output:-

    First runner incrementing i from 0 to 1
    Second runner incrementing i from 0 to 1
    Second runner incrementing i from 1 to 2
    Second runner incrementing i from 1 to 2
    

    And so on.

    Furthermore, there is a possible race condition between reading i and performing ++i since the Console.WriteLine call concatenates i and ++i. This may result in output like:-

    First runner incrementing i from 0 to 1
    Second runner incrementing i from 1 to 3
    First runner incrementing i from 1 to 2
    

    The jumbled console output which the writer has described can only result from the unpredictability of the console output and has nothing to do with a race condition on the i variable. Taking a lock on i whilst performing ++i or whilst concatenating i and ++i will not change this behaviour.

提交回复
热议问题