pthread_cond_timedwait 即使我使用绝对时间也不起作用
pthread_cond_timedwait doesn't work even if I use absolute time
我正在使用此代码尝试让 main
线程稍等片刻,但它根本不起作用。
代码如下
#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
有什么解决办法吗?非常感谢。
@Mat给出了正确答案。谢谢大家。你们真的很好
我正在使用此代码尝试让 main
线程稍等片刻,但它根本不起作用。
代码如下
#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
有什么解决办法吗?非常感谢。
@Mat给出了正确答案。谢谢大家。你们真的很好