pthreads: If I increment a global from two different threads, can there be sync issues?

后端 未结 4 1313
再見小時候
再見小時候 2020-12-19 12:53

Suppose I have two threads A and B that are both incrementing a ~global~ variable \"count\". Each thread runs a for loop like this one:

for(int i=0; i<100         


        
4条回答
  •  轮回少年
    2020-12-19 13:53

    Yes, there can be sync problems.

    As an example of the possible issues, there is no guarantee that an increment itself is an atomic operation.

    In other words, if one thread reads the value for increment then gets swapped out, the other thread could come in and change it, then the first thread will write back the wrong value:

    +-----+
    |   0 | Value stored in memory (0).
    +-----+
    |   0 | Thread 1 reads value into register (r1 = 0).
    +-----+
    |   0 | Thread 2 reads value into register (r2 = 0).
    +-----+
    |   1 | Thread 2 increments r2 and writes back.
    +-----+
    |   1 | Thread 1 increments r1 and writes back.
    +-----+
    

    So you can see that, even though both threads have tried to increment the value, it's only increased by one.

    This is just one of the possible problems. It may also be that the write itself is not atomic and one thread may update only part of the value before being swapped out.

    If you have atomic operations that are guaranteed to work in your implementation, you can use them. Otherwise, use mutexes, That's what pthreads provides for synchronisation (and guarantees will work) so is the safest approach.

提交回复
热议问题