坚持
pthread_cond_timedwait使用
clock_gettime。例如:
struct timespec ts;clock_gettime(CLOCK_REALTIME, &ts);ts.tv_sec += 10; // ten secondswhile (!some_condition && ret == 0) ret = pthread_cond_timedwait(&cond, &mutex, &ts);
如果需要,可以将其包装在函数中。
更新:根据我们的评论补充答案。
POSIX没有像Windows那样的单一API来等待事件/对象的“所有类型”。每个人都有其自己的功能。通知线程终止的最简单方法是使用原子变量/操作。例如:
主线程:
// Declare it globally (argh!) or pass by argument when the thread is createdatomic_t must_terminate = ATOMIC_INIT(0);// "Signal" termination by changing the initial valueatomic_inc(&must_terminate);
次要线程:
// While it holds the default valuewhile (atomic_read(&must_terminate) == 0) { // Keep it running...}// Do proper cleanup, if needed// Call pthread_exit() providing the exit status另一种选择是使用发送取消请求
pthread_cancel。被取消的线程必须已调用
pthread_cleanup_push才能注册任何必要的清除处理程序。这些处理程序以与注册时相反的顺序调用。永远不要
pthread_exit从清理处理程序中调用,因为它是未定义的行为。已取消线程的退出状态为
PTHREAD_CANCELED。如果您选择这种替代方法,我建议您主要阅读有关取消点和类型的信息。
最后但并非最不重要的一点是,调用
pthread_join将使当前线程阻塞,直到由参数传递的线程终止。作为奖励,您将获得线程的退出状态。



