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

相关推荐
Capricorn19881 小时前
解决全网抄 Karpathy 导致的 LLM Wiki 污染?基于知芽 Notebook Skill 的 raw/ 笔记法排障指南
大数据·论文阅读·人工智能·笔记·论文笔记
壹玖玖肆1 小时前
openGauss使用笔记
笔记
宵时待雨1 小时前
linux笔记归纳17:传输层协议UDP
linux·笔记·udp
噜~噜~噜~3 小时前
操作系统笔记-2.3.2.1 进程互斥的软件实现方法
笔记·操作系统
小弥儿3 小时前
GitHub今日热榜 | 2026-08-26:AI 大脑与知识管理扎堆
人工智能·学习·开源·github
荷蒲3 小时前
【小白量化Qbuddy】利用AI学习中文Python
人工智能·python·学习
云贝教育-郑老师3 小时前
【麒麟服务器系统交付:一个DBA的六年信创实战笔记】
服务器·笔记·dba
中科高级技工学校4 小时前
乌鲁木齐中医康复学习经历分享
大数据·学习
玖玥拾4 小时前
LeetCode 392 判断子序列
笔记·算法·leetcode
摇滚侠5 小时前
《SpringBoot 3:入门与应用实战》第 7 章 AOP 思想与实现 阅读笔记 15
java·spring boot·笔记