Do mutexes guarantee ordering of acquisition?

前端 未结 6 1240
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 15:35

A coworker had an issue recently that boiled down to what we believe was the following sequence of events in a C++ application with two threads:

  • Thread A ho

6条回答
  •  余生分开走
    2020-12-09 16:18

    How do you know this:

    While thread A is holding the mutex, thread B attempts to lock it. Since it is held, thread B is suspended.

    How do you know thread B is suspended. How do you know that it is not just finished the line of code before trying to grab the lock, but not yet grabbed the lock:

    Thread B:

    x = 17; // is the thread here?
    // or here? ('between' lines of code)
    mtx.lock();  // or suspended in here?
    // how can you tell?
    

    You can't tell. At least not in theory.

    Thus the order of acquiring the lock is, to the abstract machine (ie the language), not definable.

提交回复
热议问题