Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Suppose I have my own non-inline functions LockMutex and UnlockMutex, which are using some proper mutex - such as boost - inside. How will the compiler know not to reorder other operations with regard to calls to the LockMutex and UnlockMutex? It can not possibly know how will I implement these functions in some other compilation unit.

void SomeClass::store(int i)
{
  LockMutex(_m);
  _field = i;  // could the compiler move this around?
  UnlockMutex(_m);
}

ps: One is supposed to use instances of classes for holding locks to guarantee unlocking. I have left this out to simplify the example.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
450 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...