Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Stick to <code>pthread_cond_timedwait</code> and use <code>clock_gettime</code>. For example:</p> <pre><code>struct timespec ts; clock_gettime(CLOCK_REALTIME, &amp;ts); ts.tv_sec += 10; // ten seconds while (!some_condition &amp;&amp; ret == 0) ret = pthread_cond_timedwait(&amp;cond, &amp;mutex, &amp;ts); </code></pre> <p>Wrap it in a function if you wish.</p> <hr> <p>UPDATE: complementing the answer based on our comments.</p> <p>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:</p> <p>Main thread:</p> <pre><code>// 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(&amp;must_terminate); </code></pre> <p>Secondary thread:</p> <pre><code>// While it holds the default value while (atomic_read(&amp;must_terminate) == 0) { // Keep it running... } // Do proper cleanup, if needed // Call pthread_exit() providing the exit status </code></pre> <p>Another alternative is to send a cancellation request using <code>pthread_cancel</code>. The thread being cancelled must have called <code>pthread_cleanup_push</code> to register any necessary cleanup handler. These handlers are invoked in the reverse order they were registered. Never call <code>pthread_exit</code> from a cleanup handler, because it's undefined behaviour. The exit status of a cancelled thread is <code>PTHREAD_CANCELED</code>. If you opt for this alternative, I recommend you to read mainly about cancellation points and types.</p> <p>And last but not least, calling <code>pthread_join</code> will make the current thread block until the thread passed by argument terminates. As bonus, you'll get the thread's exit status.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload