我试图理解为什么我的互斥锁的行为不符合我的预期。
我正在调试另一个问题,并决定创建一个非常简单的可执行文件来直接测试互斥锁的行为。以下是我想到的:
#include <mutex>
#include <thread>
#include <iostream>
#include <chrono>
int main(int argc, char** argv)
{
std::mutex myMutex;
auto threadGenerator = [&] (std::string printout)
{
auto threadFunctor = [&, printout] {
int count = 0;
while (count < 300)
{
std::lock_guard<std::mutex> lock(myMutex);
std::cout << printout << std::endl;
count++;
// Sleep ensures that the other thread will be waiting on mutex
// when I release lock
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
};
return threadFunctor;
};
auto thread1Functor = threadGenerator("Thread 1 got lock");
auto thread2Functor = threadGenerator("Thread 2 got lock");
std::thread thread1(thread1Functor);
std::thread thread2(thread2Functor);
thread1.join();
thread2.join();
return 0;
}
这只是产生了两个线程,它们重复地锁定和解锁互斥锁,并打印一些输出。我添加了睡眠以强制lock_guard阻塞并使线程等待彼此。
这将产生以下输出:
Thread 1 got lock
Thread 1 got lock
Thread 1 got lock
Thread 1 got lock
Thread 1 got lock
Thread 1 got lock
Thread 1 got lock
Thread 1 got lock
Thread 1 got lock
Thread 1 got lock
Thread 1 got lock
Thread 1 got lock
最终,一旦线程1完成,线程2将再次开始获取锁。
它们不应该在线程1和线程2之间交替吗?锁应该在每个循环迭代结束时释放,这应该允许另一个线程控制互斥量。为什么没有发生?有没有办法让它发生?
std::mutex
不保证公平性。 - Pete Becker