我尝试在代码中实现pthread功能。不幸的是,我无法正确实现函数pthread_cond_timedwait()。在Linux中,一切正常。但是在Windows中,此函数不会根据设置的超时返回。这是我的简单代码:
#define HAVE_STRUCT_TIMESPEC
#include <Windows.h>
#include <future>
#include <pthread.h>
#include <time.h>
pthread_mutex_t mutex;
pthread_cond_t condVar;
void * Engine(void *)
{
unsigned long timeout = 5;
printf("timeout: %d\n", timeout);
struct timespec ts;
memset(&ts, 0, sizeof ts);
timespec_get(&ts, TIME_UTC);
char buff[100];
memset(&buff, 0, sizeof buff);
strftime(buff, sizeof buff, "%D %T", gmtime(&ts.tv_sec));
printf("ts: %s.%09ld\n", buff, ts.tv_nsec);
ts.tv_sec += timeout;
pthread_mutex_lock(&mutex);
auto t1 = std::chrono::steady_clock::now();
int rcTimedwait = pthread_cond_timedwait(&condVar, &mutex, &ts);
auto t2 = std::chrono::steady_clock::now();
pthread_mutex_unlock(&mutex);
memset(&ts, 0, sizeof ts);
timespec_get(&ts, TIME_UTC);
memset(&buff, 0, sizeof buff);
strftime(buff, sizeof buff, "%D %T", gmtime(&ts.tv_sec));
printf("ts: %s.%09ld\n", buff, ts.tv_nsec);
printf("duration %.0f\n", std::chrono::duration<double, std::milli>(t2 - t1).count());
return 0;
}
int main()
{
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&condVar, NULL);
int num1 = 1;
pthread_t thread;
pthread_create(&thread, NULL, Engine, &num1);
char ch = 0;
do
{
ch = getchar();
Sleep(1);
} while (ch != '.');
pthread_detach(thread);
pthread_cancel(thread);
pthread_cond_destroy(&condVar);
pthread_mutex_destroy(&mutex);
return 0;
}
并输出:
timeout: 5
ts: 07/24/18 07:32:21.770438500
ts: 07/24/18 07:32:26.001352700
duration 4229
timeout: 5
ts: 07/24/18 07:47:41.510704900
ts: 07/24/18 07:47:46.001373600
duration 4488
timeout: 5
ts: 07/24/18 07:47:53.190739700
ts: 07/24/18 07:47:58.001629000
duration 4808