全部博文(389)
分类: C/C++
2011-09-06 11:11:50
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变量效果相同。