pthread_mutex_t封装
来源:互联网 发布:ubuntu mysql 路径 编辑:程序博客网 时间:2024/06/05 13:12
常常需要使用pthread_mutex线程同步,每次都要使用pthread_mutex_init, pthread_mutex_lock, pthread_unlock, pthread_mutex_destroy这几个函数,干脆封装一下,以便以后重用。
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->//Mutex.cpp
#include <pthread.h>
#include <iostream>
using namespace std;
class ThreadMutex
{
public:
ThreadMutex()
{
pthread_mutex_init(&mtx, NULL);
}
~ThreadMutex()
{
pthread_mutex_destroy( &mtx );
}
inline void Lock()
{
pthread_mutex_lock( &mtx );
}
inline void UnLock()
{
pthread_mutex_unlock( &mtx );
}
private:
pthread_mutex_t mtx;
};
//以下为测试用例
ThreadMutex g_Mutex;
void *PrintMsg(void *lpPara)
{
char *msg = (char *)lpPara;
g_Mutex.Lock();
for(int i=0; i< 5; i++ )
{
cout << msg << endl;
sleep( 1 );
}
g_Mutex.UnLock();
return NULL;
}
int main()
{
pthread_t t1,t2;
//创建两个工作线程,第1个线程打印10个1,第2个线程打印10个2。
pthread_create( &t1, NULL, &PrintMsg, (void *)"First print thread" );
pthread_create( &t2, NULL, &PrintMsg, (void *)"Second print thread" );
//等待线程结束
pthread_join( t1, NULL);
pthread_join( t2, NULL);
return 0;
}
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->//Mutex.cpp
#include <pthread.h>
#include <iostream>
using namespace std;
class ThreadMutex
{
public:
ThreadMutex()
{
pthread_mutex_init(&mtx, NULL);
}
~ThreadMutex()
{
pthread_mutex_destroy( &mtx );
}
inline void Lock()
{
pthread_mutex_lock( &mtx );
}
inline void UnLock()
{
pthread_mutex_unlock( &mtx );
}
private:
pthread_mutex_t mtx;
};
//以下为测试用例
ThreadMutex g_Mutex;
void *PrintMsg(void *lpPara)
{
char *msg = (char *)lpPara;
g_Mutex.Lock();
for(int i=0; i< 5; i++ )
{
cout << msg << endl;
sleep( 1 );
}
g_Mutex.UnLock();
return NULL;
}
int main()
{
pthread_t t1,t2;
//创建两个工作线程,第1个线程打印10个1,第2个线程打印10个2。
pthread_create( &t1, NULL, &PrintMsg, (void *)"First print thread" );
pthread_create( &t2, NULL, &PrintMsg, (void *)"Second print thread" );
//等待线程结束
pthread_join( t1, NULL);
pthread_join( t2, NULL);
return 0;
}
转载自:http://www.cppblog.com/bujiwu/archive/2009/11/08/pthread_mutex.html
- pthread_mutex_t封装
- pthread_mutex_t封装
- pthread_mutex_t封装
- pthread_mutex_t封装
- POSIX pthread_mutex_t 的简单封装
- pthread_mutex_t封装的读优先锁
- pthread_mutex_t锁
- 互斥锁pthread_mutex_t
- 【linux】pthread_mutex_t
- 互斥锁--pthread_mutex_t
- Pthread_mutex_t锁
- pthread_mutex_t 互斥锁
- pthread_mutex_t死锁
- pthread_mutex_t锁
- pthread_mutex_t和pthread_cond_t
- 关于pthread_mutex_t的初始化
- 互斥锁pthread_mutex_t的使用
- 互斥锁pthread_mutex_t的使用
- Windows Server 2003远程桌面日志监控
- gdb使用及原理
- C++ 笔试题
- 【北理工研究生复试上机题】一个简单的类的实现
- 测试文章汇总
- pthread_mutex_t封装
- dbms_random.string
- 内存映射文件
- Hibernate的一些小常识(待续)
- iPhone/iPad开发札记 2012/03/09 音频
- 最大堆、最小堆、堆排序
- 详解伺服系统的控制方式
- X=X+1,X+=1,X++这三种使用方式的效率比较
- ArcSDE版本压缩之前对UNDO表空间的设置