Linux多線程編程工具庫liblmp_tool github: https://github.com/Dwyane05/liblmp_tool
使用RAII手法封裝
MutexLock& mutex_;
pthread_cond_t pcond_;
實現條件變量和互斥鎖的使用;
頭文件:
/*
* Use of this source code is governed by a BSD-style license
* that can be found in the License file.
*
* Condition.h
* Created on: May 30, 2019
* Author: cuiyongfei
*/
#ifndef LMP_TOOL_CONDITION_H
#define LMP_TOOL_CONDITION_H
#include "Mutex.h"
#include <pthread.h>
namespace lmp_tool
{
class Condition : noncopyable
{
public:
explicit Condition(MutexLock& mutex)
: mutex_(mutex)
{
MCHECK(pthread_cond_init(&pcond_, NULL));
}
~Condition()
{
MCHECK(pthread_cond_destroy(&pcond_));
}
void wait()
{
MutexLock::UnassignGuard ug(mutex_);
MCHECK(pthread_cond_wait(&pcond_, mutex_.getPthreadMutex()));
}
// returns true if time out, false otherwise.
bool waitForSeconds(double seconds);
void notify()
{
MCHECK(pthread_cond_signal(&pcond_));
}
void notifyAll()
{
MCHECK(pthread_cond_broadcast(&pcond_));
}
private:
MutexLock& mutex_;
pthread_cond_t pcond_;
};
} // namespace lmp_tool
#endif // LMP_TOOL_CONDITION_H
.cc文件
/*
* Use of this source code is governed by a BSD-style license
* that can be found in the License file.
*
* Condition.cc
* Created on: May 30, 2019
* Author: cuiyongfei
*/
#include "Condition.h"
#include <errno.h>
// returns true if time out, false otherwise.
bool lmp_tool::Condition::waitForSeconds(double seconds)
{
struct timespec abstime;
// FIXME: use CLOCK_MONOTONIC or CLOCK_MONOTONIC_RAW to prevent time rewind.
clock_gettime(CLOCK_REALTIME, &abstime);
const int64_t kNanoSecondsPerSecond = 1000000000;
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);
}