I am migrating an applciation from windows to linux. I am facing problem with respect to WaitForSingleObject and WaitForMultipleObjects interfaces.
In my application I spawn multiple threads where all threads wait for events from parent process or periodically run for every t seconds.
I have checked pthread_cond_timedwait, but we have to specify absolute time for this.
How can I implement this in Unix?
Stick to
pthread_cond_timedwaitand useclock_gettime. For example:Wrap it in a function if you wish.
UPDATE: complementing the answer based on our comments.
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:
Main thread:
Secondary thread:
Another alternative is to send a cancellation request using
pthread_cancel. The thread being cancelled must have calledpthread_cleanup_pushto register any necessary cleanup handler. These handlers are invoked in the reverse order they were registered. Never callpthread_exitfrom a cleanup handler, because it’s undefined behaviour. The exit status of a cancelled thread isPTHREAD_CANCELED. If you opt for this alternative, I recommend you to read mainly about cancellation points and types.And last but not least, calling
pthread_joinwill make the current thread block until the thread passed by argument terminates. As bonus, you’ll get the thread’s exit status.