#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
C++封装mutex condtion sem
最新推荐文章于 2025-04-12 09:30:00 发布
该代码定义了三个类,Mtx代表互斥锁,Cond表示条件变量,Sem封装了信号量。这些是多线程编程中的同步原语,用于控制对共享资源的访问和线程间的协调。Mtx提供了lock和unlock方法,Cond包含wait、timedwait、signal和broadcast方法,Sem提供wait和post操作。
7025

被折叠的 条评论
为什么被折叠?



