跳转至

线程同步机制封装类

锁机制功能

  • 多线程同步

封装功能

确保任意时刻只有一个线程执行关键代码
* 信号量
* 互斥量
* 条件变量

代码实现

locker.h
#ifndef LOCKER_H
#define LOCKER_H

#include <exception>
#include <pthread.h>
#include <semaphore.h>

//信号量
class sem {
public:
    //构造函数:信号量初始化
    sem() {
        if(sem_init(&m_sem, 0, 0) != 0) {
            throw std::exception(); //初始化失败抛出异常
        }
    }
    //有参构造函数:有信号量初值
    sem(int n) {
        if(sem_init(&m_sem, 0, n) != 0) {
            throw std::exception(); 
        }
    }

    //析构函数
    ~sem() {
        sem_destroy(&m_sem); //销毁信号量
    }

    //封装wait函数
    bool wait() {
        return sem_wait(&m_sem) == 0;
    }

    //封装post函数
    bool post() {
        return sem_post(&m_sem) == 0;
    }

private:
    sem_t m_sem;    
};

//互斥量
class locker {
public:
    locker() {
        if(pthread_mutex_init(&m_mutex, NULL) != 0) {
            throw std::exception();
        }
    }
    ~locker() {
        pthread_mutex_destroy(m_mutex);
    }

    bool lock() {
        return pthread_mutex_lock(&m_mutex) == 0;
    }
    bool unlock() {
        return pthread_mutex_unlock(&m_mutex) == 0;
    }
private:
     pthread_mutex_t m_mutex;   
};

//条件变量
class cond {
public:
    cond() {
        if(pthread_cond_init(&m_cond) != 0) {
            throw std::exception();
        }
    }
    ~cond() {
        pthread_cond_destroy(&m_cond);
    }

    bool wait(pthread_mutex_t* m_mutex) {
        int res;
        res = pthread_cond_wait(&m_cond, m_mutex);
        return ret == 0; //返回值为0,阻塞成功
    }
    //设置超时版本
    bool timewait(pthread_mutex_t* m_mutex, struct timespec t) {
        int res = 0;
        res = pthread_cond_timewait(&m_cond, m_mutex, &t);
        return res == 0;
    }
    bool signal() {
        return pthread_cond_signal(&m_cond) == 0;
    }

    //广播版本
    bool broadcast() {
        return pthread_cond_broadcast(&m_cond) == 0;
    }
private:
    pthread_cont_t m_cond;    
};
#endif

补充

  • 结构体struct timespec
    将间隔分为纳秒的结构
    • 成员:
      • time_t tv_sec:秒,vaild value are >= 0
      • long tv_nsec:纳秒,vaild value are [0,999999999]
        timespec and timespec_get()
        #include <stdio.h>
        #include <time.h>
        
        int main(void)
        {
            struct timespec ts;
            timespec_get(&ts, TIME_UTC);
            char buff[100];
            //将 秒 之前的时间格式化输入到buff中
            strftime(buff, sizeof buff, "%D %T", gmtime(&ts.tv_sec));
            printf("Current time: %s.%09ld UTC\n", buff, ts.tv_nsec);
        }