I'm coding in C (actually in OOC which is then compiled to C).
How do I instruct a thread to wait at a particular checkpoint until some other thread tells it to continue?
I'm actually using a tight loop in the thread and polling a variable I'm changing from the main thread, but I think that is not well performing, right? Besides that, when I do a tight loop in a thread, should I include a sleep in the loop to avoid consuming much cpu power just looping?
The pthread_exit() function terminates the calling thread, making its exit status available to any waiting threads. Normally, a thread terminates by returning from the start routine that was specified in the pthread_create() call which started it.
You are not required to call pthread_exit . The thread function can simply return when it's finished.
A thread cannot join itself because a deadlock would occur and it is detected by the library. However, two threads may try to join each other. They will deadlock, but this situation is not detected by the library. The pthread_join subroutine also allows a thread to return information to another thread.
pthread_create() returns zero when the call completes successfully. Any other return value indicates that an error occurred. When any of the following conditions are detected, pthread_create() fails and returns the corresponding value.
It seems that you are looking for pthread_cond_wait
and its related functions.
Here is a quote from the manpage with an example:
Consider two shared variables x and y, protected by the mutex mut, and a condition variable cond that is to be signaled whenever x becomes greater than y.
int x,y; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
Waiting until x is greater than y is performed as follows:
pthread_mutex_lock(&mut); while (x <= y) { pthread_cond_wait(&cond, &mut); } /* operate on x and y */ pthread_mutex_unlock(&mut);
Modifications on x and y that may cause x to become greater than y should signal the condition if needed:
pthread_mutex_lock(&mut); /* modify x and y */ if (x > y) pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mut);
In the end it does what you are asking for: the thread calling pthread_cond_wait(&cond)
is blocked until an other thread (your main thread for example) calls pthread_cond_broadcast(&cond)
. During this time it is just in a blocked
state and doesn't consume CPU cycles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With