linux对于互斥器的封装

来源:互联网 发布:centos更改ip地址 编辑:程序博客网 时间:2024/05/19 13:55

对于mutex封装的头文件Mutex.h为

#ifndef __MUTEX__#define __MUTEX__/*define two class MutexLock and MutexLockGuard*/#include<pthread.h>class MutexLock{private:pthread_mutex_t mutex_;public:MutexLock(){pthread_mutex_init(&mutex_,NULL);}~MutexLock(){pthread_mutex_destroy(&mutex_);}void lock(){pthread_mutex_lock(&mutex_);}void unlock(){pthread_mutex_unlock(&mutex_);}pthread_mutex_t*getPthreadMutex(){return &mutex_;}};class MutexLockGuard{private:MutexLock &mutex;public:explicit MutexLockGuard(MutexLock& mutex_):mutex(mutex_){mutex.lock();}~MutexLockGuard(){mutex.unlock();}};#endif

对于封装的类的测试为


#include<thread>#include"../Mutex.h"#include<iostream>#include<vector>using namespace std;int i=0;MutexLock mutex;void threadFunc(){MutexLockGuard t(mutex);for(int j=0;j<10;++j){++i;cout<<i<<endl;}}int main(){vector<thread> v;for(int j=0;j<10;++j){v.push_back(thread(threadFunc));}//thread t1(threadFunc);//thread t2(threadFunc);for(int j=0;j<10;++j){v[j].join();}//t1.join();//t2.join();return 0;}


0 0
原创粉丝点击