Thread can't count, giving wrong result

前端 未结 4 1077
闹比i
闹比i 2021-01-15 13:40

I wrote this piece of code

#include       /* Input/Output */
#include      /* General Utilities */
#include            


        
4条回答
  •  Happy的楠姐
    2021-01-15 13:56

    Your 2 threads access a shared resource without protection thus a race conditions apply. The increase operation isn't atomic, so you can actually have something like this in terms of machine operations:

    Thread 1                   Thread 2
    Load value of cnt        
                               Load value of cnt
    Increase value of cnt      
    Write value of cnt         Increase value of cnt
                               Write value of cnt
    

    Note, that although both threads have increased the cnt, it was actually increased only by 1. If you want the result to be deterministic, you need to protect the shared resource (cnt), e.g. by locking it prior to access.

提交回复
热议问题