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

后端 未结 4 1296
再見小時候
再見小時候 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:38

    I guess since the statement "count = count + 1" may break down into TWO assembly instructions, there is potential for the other thread to be swapped in between these two instructions? Not sure. What do you think?

    Don't think like this. You're writing C code and pthreads code. You don't have to ever think about assembly code to know how your code will behave.

    The pthreads standard does not define the behavior when one thread accesses an object while another thread is, or might be, modifying it. So unless you're writing platform-specific code, you should assume this code can do anything -- even crash.

    The obvious pthreads fix is to use mutexes. If your platform has atomic operations, you can use those.

    I strongly urge you not to delve into detailed discussions about how it might fail or what the assembly code might look like. Regardless of what you might or might not think compilers or CPUs might do, the behavior of the code is undefined. And it's too easy to convince yourself you've covered every way you can think of that it might fail and then you miss one and it fails.

提交回复
热议问题