我实现了一个基于boost互斥锁的锁宏,代码如下:
#include <boost/thread.hpp>
#include <iostream>
#define LOCK(x) if(Lock _lock_=x){}else
class Mutex{
public:
friend class Lock;
private:
boost::mutex mutex_;
void Lock(){
mutex_.lock();
};
void Unlock(){
mutex_.unlock();
};
};
class Lock{
public:
Lock(Mutex& mutex):mutex_(mutex){mutex_.Lock();};
~Lock(){mutex_.Unlock();};
operator bool() const {
return false;
}
private:
Mutex& mutex_;
};
void wait(int seconds)
{
boost::this_thread::sleep(boost::posix_time::seconds(seconds));
}
Mutex mtx;
void thread()
{
for (int i = 0; i < 5; ++i)
{
LOCK(mtx){
wait(1);
std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl;
}
}
}
int main()
{
boost::thread t1(thread);
boost::thread t2(thread);
t1.join();
t2.join();
}
我在 Mac OS 中使用clang++ -std=c++11 -stdlib=libc++ lock_raii.cc -lboost_system -lboost_thread
. 当我运行它时,有一个Segmentation fault: 11
.
它有什么问题?