OpenThreads.ReverseScopedLock是OpenSceneGraph中的一个线程锁类,它允许线程在离开作用域时自动释放锁。
class ReverseScopedLock : public OpenThreads::ScopedLock< Mutex >
{
public:
ReverseScopedLock( Mutex& mutex );
virtual ~ReverseScopedLock();
};
构造函数,传入一个Mutex对象,初始化一个ReverseScopedLock对象,会自动加锁该Mutex。
析构函数,会自动析构该对象,释放锁。
#include <osgViewer/Viewer>
#include <OpenThreads/Mutex>
#include <OpenThreads/ReverseScopedLock>
OpenThreads::Mutex mutex;
void* threadFunc(void*)
{
while(1)
{
OpenThreads::ReverseScopedLock lock(mutex);
// do something
// 当线程执行完这里的代码时,ReverseScopedLock对象会自动析构,释放锁
}
}
int main(int argc, char** argv)
{
// 主线程
pthread_t thread;
pthread_create(&thread, NULL, threadFunc, NULL);
pthread_detach(thread);
osgViewer::Viewer viewer;
while (!viewer.done())
{
// do something
}
pthread_exit(0);
return 0;
}