#include <stdio.h> #include <stdlib.h>
int flag = 1; void * THR_FN (void * arg) {while (flag) {printf ("******\n"); Sleep (10); } printf ("Sleep test thread 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 from sleep (from the suspended state to the running state), that is, the worst case is 10s, and the thread will be join. The disadvantage of using sleep: The thread cannot be woken up in time.
With the Pthread_cond_timedwait function, when the condition is reached, the thread will be join and the thread can wake up 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 (&A Mp;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); I F (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 invokes 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 calling thread must have locked the mutex. The function pthread_cond_timedwait () "Unlocks and executes the wait on the condition" (atomic operation) of the mutex.
Linux multithreaded Programming-sleep and pthread_cond_timedwait