我是靠谱客的博主 体贴彩虹,这篇文章主要介绍Scope Lock模式线程Mutex Scope Lock模式线程Mutex(一)Scope Lock模式线程Mutex(二),现在分享给大家,希望可以做个参考。
Scope Lock模式线程Mutex(一)
http://cplus.abang.com/od/cplus/a/scopedmutex1.htm
在《Unix下的线程互斥量》一文中我们使用Thread_Mutex来保护线程共享资源,但如果互斥体上锁之后没有解锁就会发生死锁。这是一个很普遍的错误,我们采用Scope Lock模式,我们构造对象Scope_Mutex,其中构造函数对互斥体加锁,析构函数对互斥体解锁。C++保证了析构函数一定会被调用,所以即使是有异常抛出,互斥体也总是会被正确的解锁。下面给出Scope_Mutex的具体实现:
class Scope_Mutex
{
private:
Thread_Mutex& mMutex;
Scope_Mutex(const Scope_Mutex&);
Scope_Mutex& operator=(const Scope_Mutex&);
public:
// 构造时对互斥量进行加锁
explicit Scope_Mutex(mMutex;& m) : mMutex;(m)
{ mMutex.lock(); }
// 析构时对互斥量进行解锁
~Scope_Mutex()
{ mMutex.unlock(); }
};
class Thread_Mutex
{
public:
/* * 构造函数 */
Thread_Mutex()
{ assert(pthread_mutex_init(&_mutex, NULL) == 0); }
/* * 析造函数 */
~Thread_Mutex()
{ //销毁互斥量 pthread_mutex_destroy(&_mutex); }
/* * 加锁 */
void lock ()
{
int error;
//锁住互斥量
error = pthread_mutex_lock(&_mutex);
if (error != 0)
{
errno = error;
perror("Mutex lock");
abort();
}
}
/* * 解锁 */
void unlock()
{
int error;
//解锁互斥量
error = pthread_mutex_unlock(&_mutex);
if (error != 0)
{
errno = error;
perror("Mutex unlock");
abort();
}
}
protected:
pthread_mutex_t _mutex;
};
下一章我们将给出如何使用Scope_Mutex。
Scope Lock模式线程Mutex(二)
http://cplus.abang.com/od/cplus/a/scopedmutex2.htm
上一章给出了Scope_Mutex的具体实现,现在,我们使用Scope_Mutex对number进行保护,具体步骤如下:
第一步:在线程函数前面使用Thread_Mutex构造Scope_Mutex
第二步:对number加1,并打印结果
第三步:在程序走出Scope_Mutex作用域,C++自动调用Scope_Mutex的析构函数来对Thread_Mutex对象进行?析构。
下面给出实现具体代码:
int number;
Thread_Mutex tm;
void* f1(void* arg)
{
int tmp_number;
while(true)
{
Scope_Mutex(tm);
tmp_number = number;
number+=1;
usleep(5);
std::cout << "thread " << pthread_self() << ": number " << tmp_number << " increment by 1 is " << number << std::endl;
}
return NULL;
}
void* f2(void* arg)
{
int tmp_number;
while(true)
{
Scope_Mutex(tm);
tmp_number = number;
number+=1;
usleep(3);
std::cout << "thread " << pthread_self() << ": number " << tmp_number << " increment by 1 is " << number << std::endl;
}
return NULL;
}
int main(void)
{
pthread_t tid1,tid2;
//create first thread;
pthread_create(&tid1, NULL, f1, NULL);
//create second thread;
pthread_create(&tid2, NULL, f2, NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
执行上述程序,发现采用Scope_Mutex来保护共享资源—number,与单独采用Thread_Mutex保护number变量效果相同。
最后
以上就是体贴彩虹最近收集整理的关于Scope Lock模式线程Mutex Scope Lock模式线程Mutex(一)Scope Lock模式线程Mutex(二)的全部内容,更多相关Scope内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复