网络编程封装mutex、cond、semaphore学习笔记

1.代码

cpp 复制代码
#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

相关推荐
西岸行者3 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
starlaky3 天前
Django入门笔记
笔记·django
勇气要爆发3 天前
吴恩达《LangChain LLM 应用开发精读笔记》1-Introduction_介绍
笔记·langchain·吴恩达
悠哉悠哉愿意3 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
勇气要爆发3 天前
吴恩达《LangChain LLM 应用开发精读笔记》2-Models, Prompts and Parsers 模型、提示和解析器
android·笔记·langchain
别催小唐敲代码3 天前
嵌入式学习路线
学习
qianshanxue113 天前
计算机操作的一些笔记标题
笔记
土拨鼠烧电路3 天前
笔记11:数据中台:不是数据仓库,是业务能力复用的引擎
数据仓库·笔记
毛小茛3 天前
计算机系统概论——校验码
学习
土拨鼠烧电路3 天前
笔记14:集成与架构:连接孤岛,构建敏捷响应能力
笔记·架构