在Linux中等效的WaitForSingleObject和WaitForMultipleObjects? [英] WaitForSingleObject and WaitForMultipleObjects equivalent in Linux?
问题描述
我正在将应用程序从Windows迁移到Linux.我在WaitForSingleObject
和WaitForMultipleObjects
接口方面遇到问题.
I am migrating an applciation from windows to linux. I am facing problem with respect to WaitForSingleObject
and WaitForMultipleObjects
interfaces.
在我的应用程序中,我产生了多个线程,其中所有线程都等待父进程的事件或每t秒定期运行一次.
In my application I spawn multiple threads where all threads wait for events from parent process or periodically run for every t seconds.
我已经检查了pthread_cond_timedwait
,但是我们必须为此指定绝对时间.
I have checked pthread_cond_timedwait
, but we have to specify absolute time for this.
如何在Unix中实现呢?
How can I implement this in Unix?
推荐答案
粘贴到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);
如果需要,可以将其包装在函数中.
Wrap it in a function if you wish.
更新:根据我们的评论对答案进行补充.
UPDATE: complementing the answer based on our comments.
POSIX没有像Windows那样的单一API来等待事件/对象的所有类型".每个人都有其自己的功能.通知线程终止的最简单方法是使用原子变量/操作.例如:
POSIX doesn't have a single API to wait for "all types" of events/objects as Windows does. Each one has its own functions. The simplest way to notify a thread for termination is using atomic variables/operations. For example:
主线程:
// 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);
辅助线程:
// 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
另一种选择是使用pthread_cancel
发送取消请求.被取消的线程必须已调用pthread_cleanup_push
来注册任何必要的清除处理程序.这些处理程序以与注册时相反的顺序调用.切勿从清理处理程序中调用pthread_exit
,因为它是未定义的行为.已取消线程的退出状态为PTHREAD_CANCELED
.如果您选择这种替代方法,我建议您主要阅读有关取消点和类型的信息.
Another alternative is to send a cancellation request using pthread_cancel
. The thread being cancelled must have called pthread_cleanup_push
to register any necessary cleanup handler. These handlers are invoked in the reverse order they were registered. Never call pthread_exit
from a cleanup handler, because it's undefined behaviour. The exit status of a cancelled thread is PTHREAD_CANCELED
. If you opt for this alternative, I recommend you to read mainly about cancellation points and types.
最后但并非最不重要的一点是,调用pthread_join
将使当前线程阻塞,直到由参数传递的线程终止.作为奖励,您将获得线程的退出状态.
And last but not least, calling pthread_join
will make the current thread block until the thread passed by argument terminates. As bonus, you'll get the thread's exit status.
这篇关于在Linux中等效的WaitForSingleObject和WaitForMultipleObjects?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!