Do mutexes guarantee ordering of acquisition?

前端 未结 6 1224
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  -上瘾入骨i
    2020-12-09 16:14

    The logic here is very simple - the thread is not preempted based on mutexes, because that would require a cost incurred for each mutex operation, which is definitely not what you want. The cost of grabbing a mutex is high enough without forcing the scheduler to look for other threads to run.

    If you want to fix this you can always yield the current thread. You can use std::this_thread::yield() - http://en.cppreference.com/w/cpp/thread/yield - and that might offer the chance to thread B to take over the mutex. But before you do that, allow me to tell you that this is a very fragile way of doing things, and offers no guarantee. You could, alternatively, investigate the issue deeper:

    1. Why is it a problem that the B thread is not started when A releases the resource? Your code should not depend on such logic.

    2. Consider using alternative thread synchronization objects like barriers (boost::barrier or http://linux.die.net/man/3/pthread_barrier_wait ) instead, if you really need this sort of logic.

    3. Investigate if you really need to release the mutex from A at that point - I find the practice of locking and releasing fast a mutex for more than one time a code smell, it usually impacts terribly the performace. See if you can group extraction of data in immutable structures which you can play around with.

    4. Ambitious, but try to work without mutexes - use instead lock-free structures and a more functional approach, including using a lot of immutable structures. I often found quite a performance gain from updating my code to not use mutexes (and still work correctly from the mt point of view)

提交回复
热议问题