Thread can't count, giving wrong result

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

I wrote this piece of code

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


        
4条回答
  •  伪装坚强ぢ
    2021-01-15 14:08

    The increment operator is usually implemented by a read-modify-write, which is non-atomic.

    A non-atomic read-modify-write across threads can sometimes do this:

    Thread 1:    Thread 2:     count
    Read count   ...           1
    Add 1        Read count    1
    Write count  Add 1         2 
    ...          Write count   2
    

    Resulting in the count being less than expected.

    If you will access a shared resource across multiple threads, you need to protect it with some kind of threading aware locking mechanism, such as a mutex.

提交回复
热议问题