C++封装mutex condtion sem

#ifndef LOCKER_H
#define LOCKER_H

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

#include <exception>
#include <iostream>

class Mtx {
 public:
  Mtx() {
    if (0 != pthread_mutex_init(&mtx_, NULL)) {
      throw std::exception();
    }
  }
  ~Mtx() { pthread_mutex_destroy(&mtx_); }

  void lock() { pthread_mutex_lock(&mtx_); }

  void unlock() { pthread_mutex_unlock(&mtx_); }

  [[NODISCARD]] auto getMutex() -> pthread_mutex_t* { return &mtx_; }

 private:
  pthread_mutex_t mtx_;
};

class Cond {
 public:
  Cond() {
    if (0 != pthread_cond_init(&cond_, NULL)) {
      throw std::exception();
    }
  }
  ~Cond() { pthread_cond_destroy(&cond_); }
  
  bool wait(pthread_mutex_t* mtx) {
    return pthread_cond_wait(&cond_, mtx) == 0;
  }

  bool timewait(pthread_mutex_t* mtx, struct timespec t) {
    return pthread_cond_timedwait(&cond_, mtx, &t) == 0;
  }

  bool singal() { return pthread_cond_signal(&cond_) == 0; }

  bool broadcast() { return pthread_cond_broadcast(&cond_) == 0; }

 private:
  pthread_cond_t cond_;
};

class Sem {
  Sem() {
    if (0 != sem_init(&sem_, 0, 0)) {
      throw std::exception();
    }
  }

  Sem(int num) {
    if (0 != sem_init(&sem_, 0, num)) {
      throw std::exception();
    }
  }

  ~Sem() { sem_destroy(&sem_); }

  bool wait() { return sem_wait(&sem_) == 0; }

  bool post() { return sem_post(&sem_) == 0; }

 private:
  sem_t sem_;
};
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值