对我来说,它似乎正在工作,除了作用域锁不是 FIFO,即第一个请求锁的线程,不是第一个获得锁的线程。我使用以下代码进行测试:
#include <boost/thread.hpp>
#include <cstdio>
boost::mutex mutex;
void threadA()
{
for (int i = 10; i > 0; )
{
boost::mutex::scoped_lock lock(mutex);
{
fprintf(stderr, "Locked by A\n");
usleep(100000);
fprintf(stderr, "Unlocked by A\n");
i--;
}
}
}
void threadB()
{
for (int i = 10; i > 0; )
{
boost::mutex::scoped_lock lock(mutex, boost::try_to_lock);
if (lock)
{
fprintf(stderr, "Locked by B\n");
usleep(100000);
fprintf(stderr, "Unlocked by B\n");
i--;
}
else
{
fprintf(stderr, "Lock failed in B\n");
usleep(100000);
}
}
}
int main(int argc, char **argv)
{
boost::thread a(threadA);
boost::thread b(threadB);
a.join();
b.join();
}
我得到了输出
Locked by A
Lock failed in B
Lock failed in B
Unlocked by A
Locked by A
Unlocked by A
Locked by A
Lock failed in B
Unlocked by A
Locked by A
Lock failed in B
Unlocked by A
Locked by A
Lock failed in B
Unlocked by A
Locked by A
Lock failed in B
Unlocked by A
Locked by A
Lock failed in B
Unlocked by A
Locked by A
Lock failed in B
Unlocked by A
Locked by A
Lock failed in B
Lock failed in B
Unlocked by A
Locked by A
Unlocked by A
Locked by B
Unlocked by B
Locked by B
Unlocked by B
Locked by B
Unlocked by B
Locked by B
Unlocked by B
Locked by B
Unlocked by B
Locked by B
Unlocked by B
Locked by B
Unlocked by B
Locked by B
Unlocked by B
Locked by B
Unlocked by B
Locked by B
Unlocked by B