Stick to pthread_cond_timedwait
and use clock_gettime
. For example:
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 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:
// 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);
Secondary thread:
// 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
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.
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…