我有两个线程试图锁定相同的boost::mutex
. 其中一个线程持续处理一些数据,另一个线程定期显示当前状态。处理线程,按照我的意图,非常频繁地释放锁并重新获取它,以便显示线程可以在需要它的时候进入并获取它。所以,很明显,我希望显示线程在下一次被进程线程释放时获取锁。但是,它并没有这样做,而是等待锁,并且仅在进程线程的许多锁释放周期后才获取它。
请检查说明我的问题的最小示例:
#include <boost/thread.hpp>
#include <iostream>
using namespace std;
using namespace boost;
mutex mut;
void process() {
double start = time(0);
while(1) {
unique_lock<mutex> lock(mut);
this_thread::sleep(posix_time::milliseconds(10));
std::cout<<".";
if(time(0)>start+10) break;
}
}
int main() {
thread t(process);
while(!t.timed_join(posix_time::seconds(1))) {
posix_time::ptime mst1 = posix_time::microsec_clock::local_time();
cout<<endl<<"attempting to lock"<<endl;
cout.flush();
unique_lock<mutex> lock(mut);
posix_time::ptime mst2 = posix_time::microsec_clock::local_time();
posix_time::time_duration msdiff = mst2 - mst1;
cout << std::endl<<"acquired lock in: "<<msdiff.total_milliseconds() << endl;
cout.flush();
}
}
编译:g++ mutextest.cpp -lboost_thread -pthread
当我运行可执行文件时,示例输出如下所示:
...................................................................................................
attempting to lock
....................................................................................................................................................................................................................................................................................................................................................................................................................................
acquired lock in: 4243
...................................................................................................
attempting to lock
........................................................................................................
acquired lock in: 1049
...................................................................................................
attempting to lock
........................................................................................................................
acquired lock in: 1211
....................................
如您所见,在最坏的情况下,显示线程会等待 424 个锁释放周期,然后才开始捕获锁。
我显然以错误的方式使用互斥锁,但解决这个问题的常用方法是什么?