|
# Include <stdio. h>
# Include <stdlib. h>
Int flag = 1;
Void * thr_fn (void * Arg ){
While (FLAG ){
Printf ("******* \ n ");
Sleep (10 );
}
Printf ("sleepTestThread exit \ n ");
}
Int main (){
Pthread_t thread;
If (0! = Pthread_create (& Thread, null, thr_fn, null )){
Printf ("error when create pthread, % d \ n", errno );
Return 1;
}
Char C;
While (C = getchar ())! = 'Q ');
Printf ("Now terminate the thread! \ N ");
Flag = 0;
Printf ("wait for thread to exit \ n ");
Pthread_join (thread, null );
Printf ("Bye \ n ");
Return 0;
} |
After entering Q, you need to wait for the thread to wake up from sleep (from pending to running), that is, the thread will be joined after 10 s in the worst case. Disadvantages of using sleep: the thread cannot be awakened in time.
The pthread_cond_timedwait function is used. When the condition is reached, the thread is joined and the thread can be awakened in time. The implementation is as follows:
|
# Include <stdio. h>
# Include <sys/time. h>
# Include <unistd. h>
# Include <pthread. h>
# Include <errno. h>
Static pthread_t thread;
Static pthread_cond_t cond;
Static pthread_mutex_t mutex;
Static int flag = 1;
Void * thr_fn (void * Arg)
{
Struct timeval now;
Struct timespec outtime;
Pthread_mutex_lock (& mutex );
While (FLAG ){
Printf ("***** \ n ");
Gettimeofday (& now, null );
Outtime. TV _sec = now. TV _sec + 5;
Outtime. TV _nsec = now. TV _usec * 1000;
Pthread_cond_timedwait (& cond, & mutex, & outtime );
}
Pthread_mutex_unlock (& mutex );
Printf ("cond thread exit \ n ");
}
Int main (void)
{
Pthread_mutex_init (& mutex, null );
Pthread_cond_init (& cond, null );
If (0! = Pthread_create (& Thread, null, thr_fn, null )){
Printf ("error when create pthread, % d \ n", errno );
Return 1;
}
Char C;
While (C = getchar ())! = 'Q ');
Printf ("Now terminate the thread! \ N ");
Pthread_mutex_lock (& mutex );
Flag = 0;
Pthread_cond_signal (& Cond );
Pthread_mutex_unlock (& mutex );
Printf ("wait for thread to exit \ n ");
Pthread_join (thread, null );
Printf ("Bye \ n ");
Return 0;
} |
The pthread_cond_timedwait () function blocks the thread that calls the function and waits for the condition specified by cond to be triggered (pthread_cond_broadcast () or pthread_cond_signal ()).
When pthread_cond_timedwait () is called, the call thread must have locked the mutex. The pthread_cond_timedwait () function unlocks mutex and performs an atomic operation on the condition ).