Compiler reordering around mutex boundaries?

自古美人都是妖i 提交于 2019-11-29 06:59:01

It can not possibly know how will I implement these functions in some other compilation unit.

This is the key - since the compiler cannot know (in general) about the implementation of the function calls, it can't move the store to _field outside those function calls.

Generally, since _field is accessible outside of SomeClass::store() (it's not a local), the compiler can't know whether or not it's modified by the external function, therefore it must perform the store to _field between the function call sequence points.

The underlying hardware platform might need some attention in the form of memory barriers or cache flushes to deal with caching or out of order operations that occur in the hardware. The platform's implementation of the mutex APIs will deal with those issues if necessary.

In general, a compiler will not move code around unless it knows with certainty that doing so will not affect run-time behavior.

As it is written, if the functions are not inline, the compiler won't move the variable assignation, as the call may be unrelated to the _field variable, but it has to preserve the strict order of calls. If, however, the compiler decides to inline the calls, I think it will treat them as blocks of independent code, that is, it will only reorder instructions within the same code unit (the inlined function itself) but not with the following or preceding code (the assignation to the _field variable).

You're right, that code is correct and safe. I did think of a "code joke," though.

pthread_mutex_lock( &mx ) + foo() + pthread_mutex_unlock( &mx );

If compiler was doing so that'd be a bad compiler. ;-)

If the compiler can't guarantee that the function calls won't have side effects that will modify the variables between the calls, it can't move the code. If the variable is a local variable and you've never taken a reference or created a pointer to it, the compiler might assume it's safe to move; I don't know.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!