网络编程封装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

相关推荐
LinXunFeng5 天前
Obsidian - 使用 Share Note 分享笔记并自部署
前端·笔记·github
通信小呆呆9 天前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
H__Rick9 天前
自动对焦学习-3
人工智能·学习·计算机视觉
Daisy Lee9 天前
量化学习-第1章-什么是量化金融
学习·金融·datawhale
Alsn869 天前
等待学习-学习目录:Docker 容器安全攻防
学习·安全·docker
YM52e9 天前
买菜计算器小应用 - HarmonyOS ArkUI 开发实战-PC版本
学习·华为·harmonyos·鸿蒙·鸿蒙系统
小雨下雨的雨9 天前
HarmonyOS ArkUI训练营入门-组件掌握系列-Animation 动画效果实现-PC版本
学习·华为·harmonyos·鸿蒙
闪闪发亮的小星星9 天前
高斯光以及高斯光公式解释
笔记
cqbzcsq9 天前
CellFlow虚拟细胞论文阅读
论文阅读·人工智能·笔记·学习·生物信息
YangYang9YangYan9 天前
2026初入职场学习数据分析的价值
学习·数据挖掘·数据分析