在Linux中等效的WaitForSingleObject和WaitForMultipleObjects

Poo*_*rna 27 c linux multithreading porting synchronization

我正在将一个applciation从windows迁移到linux.我面临着关于WaitForSingleObjectWaitForMultipleObjects接口的问题.

在我的应用程序中,我生成多个线程,其中所有线程等待来自父进程的事件或每隔t秒定期运行.

我已经检查过pthread_cond_timedwait,但我们必须为此指定绝对时间.

我怎样才能在Unix中实现它?

jwe*_*ich 12

坚持pthread_cond_timedwait并使用clock_gettime.例如:

struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 10; // ten seconds
while (!some_condition && ret == 0)
    ret = pthread_cond_timedwait(&cond, &mutex, &ts);
Run Code Online (Sandbox Code Playgroud)

如果您愿意,请将其包裹在一个功能中.


更新:根据我们的评论补充答案.

POSIX没有一个API可以像Windows一样等待"所有类型"的事件/对象.每个人都有自己的功能.通知线程终止的最简单方法是使用原子变量/操作.例如:

主线程:

// Declare it globally (argh!) or pass by argument when the thread is created
atomic_t must_terminate = ATOMIC_INIT(0);

// "Signal" termination by changing the initial value
atomic_inc(&must_terminate); 
Run Code Online (Sandbox Code Playgroud)

次要线程:

// While it holds the default value
while (atomic_read(&must_terminate) == 0) {
    // Keep it running...
}
// Do proper cleanup, if needed
// Call pthread_exit() providing the exit status
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用发送取消请求pthread_cancel.被取消的线程必须已调用pthread_cleanup_push以注册任何必要的清理处理程序.这些处理程序按照它们注册的相反顺序调用.永远不要pthread_exit从清理处理程序调用,因为它是未定义的行为.已取消线程的退出状态为PTHREAD_CANCELED.如果您选择此替代方案,我建议您主要阅读取消点和类型.

最后但并非最不重要的是,调用pthread_join将使当前线程阻塞,直到通过参数传递的线程终止.作为奖励,您将获得线程的退出状态.


Mah*_*dsi 12

值得一提的是,我们(NeoSmart Technologies)刚刚发布了一个名为pevents的开源(MIT许可)库,它在POSIX上实现WIN32手动和自动重置事件,并包括WaitForSingleObject和WaitForMultipleObjects克隆.

虽然我个人建议您在POSIX机器上编码时使用POSIX多线程和信令范例,但如果您需要,pevents会为您提供另一种选择.