Semaphore thread synchronization of linux-

1. Task: any character user input from a terminal and counting the number of characters displayed, the end of the input end

2. Multithread: main thread to obtain user input and determines whether to exit, the sub-thread count

. 1 #include <stdio.h>
 2 #include < String .h>
 . 3 #include <stdlib.h>
 . 4 #include <pthread.h>
 . 5 #include <semaphore.h>
 . 6  
. 7  char buf [ 200 is ] = { 0 };
 . 8  sem_t SEM;
 . 9  void * FUNC ( void * Arg);
 10  // sub-thread programs, the role of statistics is the number of characters and prints buf 
. 11  void * FUNC ( void * Arg)
 12 is  {
 13 is      // child thread should first have cycles to be blocked in a loop while waiting for the main thread activated;
 14      //After being activated sub-thread to acquire the character length of buf, then print; blocked again after printing 
15      of sem_wait (& SEM);
 16      the while (a strncmp (buf, " End " , . 3 !) = 0 )
 . 17      {
 18 is          the printf ( " enter a% d characters \ n- " , strlen (buf));
 . 19          Memset (buf, 0 , the sizeof (buf));
 20 is          of sem_wait (& SEM);
 21 is      }
 22 is      the pthread_exit (NULL); 
 23 is  }
 24  
25  int main ( void )
26 is  {
 27      int RET = - . 1 ;
 28      pthread_t TH = - . 1 ;
 29      
30      sem_init (& SEM, 0 , 0 );
 31 is      
32      RET = pthread_create (& TH, NULL, FUNC, NULL);
 33 is      IF ! (RET = 0 )
 34 is      {
 35          the printf ( " pthread_create error \ n " );
 36          Exit (- . 1 );
 37 [      }
 38 is      
39      the printf ( " Please enter characters, carriage return \ n" );
 40      the while (Scanf ( " % S " , buf))
 41 is      {
 42 is          // determine whether the user input is not End, if it is, then exit; if not, it 
43 is          IF ! (A strncmp (buf, " End " , 3 ))
 44          {
 45              // input is end 
46 is              the printf ( " end of program \ n- ' );
 47              sem_post (& SEM); // activation semaphore 
48              BREAK ;
 49          }
 50          // main thread receives the user after the input string and confirms End not, go signal activator thread count
51          // child thread is blocked, the main thread can be activated, that is synchronization of threads
 52          // semaphores can be used to achieve this synchronization thread 
53 is          sem_post (& SEM); // activation semaphore 
54 is          
55      }
 56 is      
57 is      // recovering sub-thread 
58      the printf ( " waiting for recovery of child threads \ n-. " );
 59      RET = pthread_join (TH, NULL);    
 60      IF (! RET = 0 )
 61 is      {
 62 is          the printf ( " . pthread_join error \ n- " );
 63 is          Exit (- . 1 );
 64      }
65      printf ( " child thread recovery success \ the n-. " );
 66      
67      sem_destroy (& sem);
 68      return  0 ;
 69 }

 

Guess you like

Origin www.cnblogs.com/jiangtongxue/p/11307314.html