C# Threading: a race condition example

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

    When I run this (on a dualcore), my output is

    First runner incrementing i from 0 to 1
    Second runner incrementing i from 1 to 2
    First runner incrementing i from 2 to 3
    Second runner incrementing i from 3 to 4
    First runner incrementing i from 4 to 5
    Second runner incrementing i from 5 to 6
    First runner incrementing i from 6 to 7
    Second runner incrementing i from 7 to 8
    First runner incrementing i from 8 to 9
    Second runner incrementing i from 9 to 10
    

    As I would have expected. You are running two loops, both executing Sleep(100). That is very ill suited to demonstrate a race-condition.

    The code does have a race condition (as VoteyDisciple describes) but it is very unlikely to surface.

    I can't explain the lack of order in your output (is it a real output?), but the Console class will synchronize output calls.

    If you leave out the Sleep() calls and run the loops 1000 times (instead of 10) you might see two runners both incrementing from 554 to 555 or something.

提交回复
热议问题