bool timed_wait(lock_type& lock,boost::system_time const& abs_time)?,c++,boost,boost-thread"/>

首页 > 解决方案 > 这是使用模板的正确方法bool timed_wait(lock_type& lock,boost::system_time const& abs_time)?

问题描述

我将使用 boost 中的 timed_wait() 来等待条件变量。我无法从 boost 文档中找到好的和平代码,并找到了一些堆栈溢出引用。在这些示例中,我发现了以下两种用途。

  1. bool bDoneInTime = g_Condition.timed_wait(lockedCondLock, boost::system_time() + boost::posix_time::seconds(1));通过将延迟添加到系统时间来传递延迟。
  2. bool bDoneInTime = g_Condition.timed_wait(lockedCondLock, boost::posix_time::seconds(1));只是通过延迟

我在下面的示例代码中都试过了,只是为了测试

#include <string>
#include <vector>
#include <iostream>
#include <thread>
#include <time.h>
#include <sys/time.h>
#include <pthread.h>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>


static boost::mutex g_ConditionMutex;
typedef boost::unique_lock<boost::mutex> lock_t;
static boost::condition_variable g_Condition;

using namespace std;


void* fun(void* arg)
{
    printf("\nIn thread\n");

    lock_t lock(g_ConditionMutex);
    printf("Sleep second\n");
    g_Condition.timed_wait(lock, boost::posix_time::seconds(1));

    printf("Sleep second as zebra driver\n");
    g_Condition.timed_wait(lock, boost::system_time() + boost::posix_time::seconds(1));

    printf("\nDone\n");
}


int main(int argc, char *argv[])
{
    pthread_t thread;
    void *ret;

    pthread_create(&thread, NULL, fun, NULL);
    printf("Sleep 10 sec main\n");
    sleep(10);
    printf("Notify\n");
    g_Condition.notify_one();

    pthread_join(thread,&ret);
return 0;
}

两种方法都有效,但我对如何template<typename lock_type> bool timed_wait(lock_type& lock,boost::system_time const& abs_time)从 boost 中使用它感到困惑。

请有人帮我找出正确的方法。

标签: c++boostboost-thread

解决方案


推荐阅读