1

我尝试使用以下逻辑(一种伪代码)实现pthread

pthread_mutex_t mutex;

threadA()
{
    lock(mutex);
    // do work
    timed_lock(mutex, current_abs_time + 1 minute);
}

threadB()
{
    // do work in more than 1 minute
    unlock(mutex);
}

我确实希望threadA做这项工作并等到threadB信号但不超过 1 分钟。我在 Win32 中做了很多类似的事情,但坚持使用 pthreads:一个timed_lock部分立即(不是 1 分钟)返回代码ETIMEDOUT

有没有简单的方法来实现上面的逻辑?

即使下面的代码ETIMEDOUT立即返回

pthread_mutex_t m;
// Thread A
pthread_mutex_init(&m, 0);
pthread_mutex_lock(&m);
// Thread B
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
struct timespec time = {now.tv_sec + 5, now.tv_nsec};
pthread_mutex_timedlock(&m, &time); // immediately return ETIMEDOUT

有谁知道为什么?我也尝试过gettimeofday功能

谢谢

4

3 回答 3

1

我用条件变量相对于其他规则(使用包装互斥锁、布尔标志等)实现了我的逻辑。谢谢大家的评论。

于 2014-12-08T21:37:33.007 回答
0

尝试这样的事情:

class CmyClass
{
   boost::mutex mtxEventWait;
   bool WaitForEvent(long milliseconds);
   boost::condition cndSignalEvent;
};

bool CmyClass::WaitForEvent(long milliseconds)
{
   boost::mutex::scoped_lock mtxWaitLock(mtxEventWait);
   boost::posix_time::time_duration wait_duration = boost::posix_time::milliseconds(milliseconds); 
   boost::system_time const timeout=boost::get_system_time()+wait_duration; 
   return cndSignalEvent.timed_wait(mtxEventWait,timeout); // wait until signal Event 
}

// 所以为了等待然后调用 WaitForEvent 方法

WaitForEvent(1000); // it will timeout after 1 second

// 这就是事件的信号方式:

cndSignalEvent.notify_one();
于 2016-11-30T09:28:58.083 回答
0

对于第二段代码:AFAIK pthread_mutex_timedlock 仅适用于 CLOCK_REALTIME。

  • CLOCK_REALTIME 是自 1970 年 1 月 1 日以来的秒数
  • CLOCK_MONOTONIC 通常自启动以来

在这些前提下,超时设置是 1970 年的几秒钟,因此是过去的。

于 2019-08-09T12:17:56.157 回答