迪庆藏族自治州网站建设_网站建设公司_营销型网站_seo优化
2026/1/10 1:37:43 网站建设 项目流程

1.代码

#ifndef LOCKER_H #define LOCKER_H #include<exception> #include<pthread.h> #include<semaphore.h> class locker{ public: locker(){ if(pthread_mutex_init(&mutex,NULL)!=0){ throw std::exception(); } } ~locker(){ pthread_mutex_destroy(&mutex); } bool lock(){ return pthread_mutex_lock(&mutex)==0; } bool unlock(){ return pthread_mutex_unlock(&mutex)==0; } pthread_mutex_t *get(){ return &mutex; } private: pthread_mutex_t mutex; }; class cond{ public: cond(){ if(pthread_cond_init(&m_cond,NULL)!=0){ throw std::exception(); } } ~cond(){ pthread_cond_destroy(&m_cond); } bool wait(pthread_mutex_t *mutex){ // int ret=0; //ret=pthread_cond_wait(&m_cond,mutex); //return ret==0; return pthread_cond_wait(&m_cond,mutex)==0; } bool timewait(pthread_mutex_t *mutex,timespec t){ //int ret=0; //ret=pthread_cond_timedwait(&m_cond,mutex,&t); //return ret==0; return pthread_cond_timedwait(&m_cond,mutex,&t)==0; } bool signal(){ return pthread_cond_signal(&m_cond)==0; } bool broadcast(){ return pthread_cond_broadcast(&m_cond)==0; } private: pthread_cond_t m_cond; }; class sem{ public: sem(){ if(sem_init(&m_sem,0,0)!=0){ throw std::exception(); } } sem(int num){ if(sem_init(&m_sem,0,num)!=0){ throw std::exception(); } } ~sem(){ sem_destroy(&m_sem); } bool wait(){ return sem_wait(&m_sem)==0; } bool post(){ return sem_post(&m_sem)==0; } private: sem_t m_sem; }; #endif

2.知识点

1.使用构造和析构来封装对锁的初始化和销毁的处理。

2.对于cond

pthread_cond_wait和pthread_cond_signal

参数是要绑定的锁的指针。

3.对于sem

有sem_wait和sem_post

4.对于成功的判别主要是通过==0

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询