mywaitcondition_unix.cpp

来自「linux下线程的创建、管理」· C++ 代码 · 共 103 行

CPP
103
字号
#include <pthread.h>#include <sys/time.h>typedef pthread_mutex_t MY_MUTEX_T;#include "mywaitcondition.h"#include "mymutex.h"#include "mymutex_p.h"#include <errno.h>#include <string.h>struct MyWaitConditionPrivate{  pthread_cond_t cond;};MyWaitCondition::MyWaitCondition (){  d = new MyWaitConditionPrivate;  pthread_cond_init (&d->cond, NULL);}MyWaitCondition::~MyWaitCondition (){  int ret = pthread_cond_destroy (&d->cond);  if (ret)  {    pthread_cond_broadcast (&d->cond);  }  delete d;}void MyWaitCondition::wakeOne (){  pthread_cond_signal (&d->cond);}void MyWaitCondition::wakeAll (){  pthread_cond_broadcast (&d->cond);}bool MyWaitCondition::wait (unsigned long time){  pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;  pthread_mutex_lock (&mutex);  int ret;  if (time != ULONG_MAX)  {    struct timeval tv;    gettimeofday (&tv, 0);    timespec ti;    ti.tv_nsec = (tv.tv_usec * 1000) + (time % 1000) * 1000;    ti.tv_sec = tv.tv_sec + (time / 1000) + (ti.tv_nsec / 1000000000);    ti.tv_nsec %= 1000000000;    ret = pthread_cond_timedwait (&d->cond, &mutex, &ti);  }  else    ret = pthread_cond_wait (&d->cond, &mutex);  pthread_mutex_unlock (&mutex);  return (ret == 0);}bool MyWaitCondition::wait (MyMutex * mutex, unsigned long time){  if (!mutex)    return false;  int ret;  if (time != ULONG_MAX)  {    struct timeval tv;    gettimeofday (&tv, 0);    timespec ti;    ti.tv_nsec = (tv.tv_usec * 1000) + (time % 1000) * 1000;    ti.tv_sec = tv.tv_sec + (time / 1000) + (ti.tv_nsec / 1000000000);    ti.tv_nsec %= 1000000000;    ret = pthread_cond_timedwait (&d->cond, &mutex->d->handle, &ti);  }  else    ret = pthread_cond_wait (&d->cond, &mutex->d->handle);  return (ret == 0);}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?