【发布时间】:2021-04-05 07:01:03
【问题描述】:
我正在使用此代码尝试让mainthread 等待一段时间,但它根本不起作用。
代码如下。
#include <string>
#include <cstring>
#include <string.h>
#include <iostream>
#include <pthread.h>
#include <sys/time.h>
using namespace std;
int64_t get_current_millis(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
return (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
int main()
{
pthread_mutex_t Mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t Condition = PTHREAD_COND_INITIALIZER;
uint64_t start_ts = get_current_millis();
struct timeval now;
struct timespec interval;
pthread_mutex_lock(&Mutex);
gettimeofday(&now, NULL);
interval.tv_sec = now.tv_sec;
interval.tv_nsec = now.tv_usec * 1000;
interval.tv_sec += 5;
pthread_cond_timedwait(&Condition, &Mutex, &interval);
pthread_mutex_unlock(&Mutex);
uint64_t end_ts = get_current_millis();
std::cout << "wait " << (end_ts - start_ts)/1000 << "s" << std::endl;
return 0;
}
如您所见,我使用绝对时间。但它会打印出来:
wait 0s
有什么解决办法吗?非常感谢。
【问题讨论】:
-
在 C++ 中有
std::condition_variable。请选择语言。 -
你至少应该检查
pthread_cond_timedwait返回的值。你确定你不只是得到一个虚假的唤醒吗? -
您是否使用
-pthread编译(和链接)(如果使用GCC 或clang)? -
gettimeofday(&now, NULL);改为使用clock_gettime(CLOCK_REALTIME -
谢谢。你们真的很好。我忘了加
-lpthread。添加后效果很好。