这段代码演示了互斥锁在两个线程之间共享,但一个线程几乎一直拥有它。
#include <thread>
#include <mutex>
#include <iostream>
#include <unistd.h>
int main ()
{
std::mutex m;
std::thread t ([&] ()
{
while (true)
{
{
std::lock_guard <std::mutex> thread_lock (m);
sleep (1); // or whatever
}
std::cerr << "#";
std::cerr.flush ();
}
});
while (true)
{
std::lock_guard <std::mutex> main_lock (m);
std::cerr << ".";
std::cerr.flush ();
}
}
在 Ubuntu 18.04 4.15.0-23-generic 上使用 g++ 7.3.0 编译。
输出是#
和.
字符的混合,表明互斥体正在共享,但模式令人惊讶。通常是这样的:
.......#####..........................##################......................##
即thread_lock
锁定互斥锁很长时间。几秒甚至几十秒后,接收方main_lock
(短暂地)接收控制权,然后thread_lock
将其取回并保留很长时间。打电话std::this_thread::yield()
不会改变任何事情。
为什么两个互斥锁获得锁定的可能性不同,如何使互斥锁以平衡的方式共享?