Problem with pThread sync issue

前端 未结 5 1087
温柔的废话
温柔的废话 2020-12-29 00:27

I am facing a sync issue with pthread. threadWaitFunction1, is a thread wait function. I expect line no. 247 flag = 1 to be executed only after 243-246 has fini

5条回答
  •  旧时难觅i
    2020-12-29 01:18

    This could be because the compiler has optimized things and put your assignment to your flag before the thread mutex. If you want to guarantee order of execution, (something which is not normally guaranteed, on the only condition that the visible behaviour of your program does not change due to optimizations), you use a memory barrier to make sure that the instructions you want to be executed in the order you write them, are executed only in that order.

    Here is a very interesting, though rather technical and long, article on how memory barriers work and what they do and don't do. It's written for Linux, but the basic principles remain the same.

    EDIT:

    The lock is an implicit memory barrier, by the link I gave earlier, so no memory barrier is needed.

提交回复
热议问题