- 互斥锁(muduo库简单的封装)
将muduo库的线程id的操作去除的简单版本
#define MCHECK(ret) ({ __typeof__ (ret) errnum = (ret); assert(errnum == 0); (void) errnum;})
class MutexLock : noncopyable
{
public:
MutexLock()
{
MCHECK(pthread_mutex_init(&mutex_, NULL));
}
~MutexLock()
{
MCHECK(pthread_mutex_destroy(&mutex_));
}
void lock()
{
MCHECK(pthread_mutex_lock(&mutex_));
}
void unlock()
{
MCHECK(pthread_mutex_unlock(&mutex_));
}
pthread_mutex_t* getPthreadMutex()
{
return &mutex_;
}
private:
pthread_mutex_t mutex_;
};
链接:[http:
class MutexLockGuard : noncopyable
{
public:
explicit MutexLockGuard(MutexLock& mutex)
: mutex_(mutex)
{
mutex_.lock();
}
~MutexLockGuard()
{
mutex_.unlock();
}
private:
MutexLock& mutex_;
};
#define MutexLockGuard(x) error "Missing guard object name"
- 条件变量类封装
class Condition : noncopyable
{
public:
explicit Condition(MutexLock& mutex)
: mutex_(mutex)
{
MCHECK(pthread_cond_init(&pcond_, NULL));
}
~Condition()
{
MCHECK(pthread_cond_destroy(&pcond_));
}
void wait()
{
MCHECK(pthread_cond_wait(&pcond_,mutex_.getPthreadMutex()));
}
void notify()
{
MCHECK(pthread_cond_signal(&pcond_));
}
void notifyAll()
{
MCHECK(pthread_cond_broadcast(&pcond_));
}
bool waitForSeconds(double seconds)
{
struct timespec abstime;
clock_gettime(CLOCK_REALTIME, &abstime);
const int64_t kNanoSecondsPerSecond = 1e9;
int64_t nanoseconds = static_cast<int64_t>(seconds * kNanoSecondsPerSecond);
abstime.tv_sec += static_cast<time_t>((abstime.tv_nsec + nanoseconds) / kNanoSecondsPerSecond);
abstime.tv_nsec = static_cast<long>((abstime.tv_nsec + nanoseconds) % kNanoSecondsPerSecond);
MutexLock::UnassignGuard ug(mutex_);
return ETIMEDOUT == pthread_cond_timedwait(&pcond_, mutex_.getPthreadMutex(), &abstime);
}
private:
MutexLock& mutex_;
pthread_cond_t pcond_;
};
- CountDownLatch类:
可实现子进程等待主进程发起命令后竞争执行
(主线程调用countDown,子线程调用wait)
也可实现主线程等待子进程初始化完成后在执行
(主线程调用wait,子线程调用countDown)
class CountDownLatch : noncopyable
{
public:
explicit CountDownLatch(int count);
void wait()
{
MutexLockGuard lock(mutex_);
while (count_ > 0)
{
condition_.wait();
}
}
void countDown()
{
MutexLockGuard lock(mutex_);
--count_;
if (count_ == 0)
{
condition_.notifyAll();
}
}
int getCount() const
{
MutexLockGuard lock(mutex_);
return count_;
}
private:
mutable MutexLock mutex_;
Condition condition_;
int count_;
};