Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1237733
  • 博文数量: 389
  • 博客积分: 2874
  • 博客等级: 少校
  • 技术积分: 3577
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-24 10:34
文章分类

全部博文(389)

文章存档

2020年(2)

2018年(39)

2017年(27)

2016年(3)

2015年(55)

2014年(92)

2013年(54)

2012年(53)

2011年(64)

分类: C/C++

2011-09-06 11:11:50

Scope Lock模式线程Mutex(一)
作者:帮手朱翔
问帮手给我写信rss 邮件订阅

网站承诺:阿邦网坚持写作客观独立的立场,永远不受金钱影响。秉承为人民生活服务的宗旨,与您分享特邀帮手的经验和知识,帮您解决生活问题,提高生活品质。本文系阿邦网独家稿件,未经许可,任何媒体和个人,不得全部或部分转载,违者必究。
在《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_Mutex对number进行保护,具体步骤如下:
第一步:在线程函数前面使用Thread_Mutex构造Scope_Mutex
  第二步:对number加1,并打印结果
第三步:在程序走出Scope_Mutex作用域,C++自动调用Scope_Mutex的析构函数来对Thread_Mutex对象进行析构。

下面给出实现具体代码:

#include
#include
#include

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变量效果相同。

阅读(682) | 评论(0) | 转发(0) |
0

上一篇:boost asio

下一篇:ThreadPool分析

给主人留下些什么吧!~~