WaitForSingleObject的和WaitForMultipleObjects的相当于在Linux [英] WaitForSingleObject and WaitForMultipleObjects equivalent in linux

查看:1163
本文介绍了WaitForSingleObject的和WaitForMultipleObjects的相当于在Linux的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从窗户迁移的applciation到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没有一个单一的API等待作为Windows不事件/对象的所有类型的。每个人都有自己的功能。最简单的方法来通知终止使用原子变量/动作的线程。例如:

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.

这篇关于WaitForSingleObject的和WaitForMultipleObjects的相当于在Linux的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆