用c++简单的封装线程c中互斥锁

来源:互联网 发布:工业控制网络视频 编辑:程序博客网 时间:2024/06/05 16:27
#include <iostream>#include <pthread.h>#include <stdio.h>//用c++简单的封装互斥锁class LOCK{private:pthread_mutex_t mutex;public:LOCK();virtual ~LOCK();void lock_t();void unlock_t();void trylock_t();};LOCK::LOCK(){pthread_mutex_init(&mutex, NULL);   //在构造函数中直接初始化互斥锁}LOCK::~LOCK(){}void LOCK::lock_t(){pthread_mutex_lock(&mutex);}void LOCK::unlock_t(){pthread_mutex_unlock(&mutex);}void LOCK::trylock_t(){pthread_mutex_trylock(&mutex);}//全局变量int a = 0;//创建锁对象LOCK lock;//线程回调函数void * thread1(void * arg){while(1){printf("I am thread1\n");lock.lock_t();a++;printf("thread1-a === %d\n",a);lock.unlock_t();sleep(1);}}void * thread2(void *arg){while(1){printf("I am thread2\n");lock.lock_t();a++;printf("thread2-a === %d\n",a);lock.unlock_t();sleep(2);}}int main(int argc,char * argv[]){//创建两个线程pthread_t test1;    pthread_t test2;pthread_create(&test1,NULL,thread1,NULL);pthread_create(&test2,NULL,thread2,NULL);pthread_join(test1,NULL);pthread_join(test2,NULL);return 0;}