Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop and continue a pthread?

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?

like image 360
Damian Avatar asked Jan 25 '11 14:01

Damian


People also ask

How do you end a Pthread?

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.

Is Pthread exit necessary?

You are not required to call pthread_exit . The thread function can simply return when it's finished.

Can a Pthread join itself?

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.

Does pthread_create return?

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.


1 Answers

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.

like image 174
Arnaud Le Blanc Avatar answered Sep 30 '22 12:09

Arnaud Le Blanc