Linux多线程C++工具库:liblmp_tool -- 条件变量Condition

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

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

// 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(seconds * kNanoSecondsPerSecond);

  abstime.tv_sec += static_cast((abstime.tv_nsec + nanoseconds) / kNanoSecondsPerSecond);
  abstime.tv_nsec = static_cast((abstime.tv_nsec + nanoseconds) % kNanoSecondsPerSecond);

  MutexLock::UnassignGuard ug(mutex_);
  return ETIMEDOUT == pthread_cond_timedwait(&pcond_, mutex_.getPthreadMutex(), &abstime);
}

 

 

 

 

 

你可能感兴趣的:(C++)