c++ - 这是使用模板的正确方法bool timed_wait(lock_type& lock,boost::system_time const& abs_time)?
问题描述
我将使用 boost 中的 timed_wait() 来等待条件变量。我无法从 boost 文档中找到好的和平代码,并找到了一些堆栈溢出引用。在这些示例中,我发现了以下两种用途。
bool bDoneInTime = g_Condition.timed_wait(lockedCondLock, boost::system_time() + boost::posix_time::seconds(1));
通过将延迟添加到系统时间来传递延迟。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 中使用它感到困惑。
请有人帮我找出正确的方法。
解决方案
推荐阅读
- jquery - 如何通过使用jquery单击复选框来对项目列表进行排序?
- python - 让 Flask-Login 与 unittest 一起工作
- java - 根据 Big-O 表示法的增长顺序
- swift - 使用 DispatchQueue.asyncAfter 延迟调用
- c# - 如何在 Xamarin Forms 中的按钮上创建网格
- python - 仅在带有熊猫的组的最后一行中添加组的最小值
- html - 停止 div 与容器重叠
- reactjs - 我在 app.js 中编译的松露合约的导入错误
- python - pip 的问题,SSLException
- php - PHP 数组(只有一个结果)