#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