Let's start with a few key steps to the thread sync semaphore!
1. Define and initialize the semaphore.
(1) sem_t Bin_sem;
(2) res = Sem_init (&bin_sem,0,0);
Detailed steps to view the man help page
2, the use of signal volume
(1) Signal volume plus 1 operation. Sem_post (&Bin_sem);
(2) Semaphore waits and minus 1 operation. Sem_wait (&Bin_sem);
After initialization, the general wait state, after performing an operation plus 1, and another operation before the execution of the wait operation. If there are multiple threads, usually one thread adds 1, and the other is waiting.
The deadlock problem with semaphores is not discussed here.
3, the use of the instant destruction.
Sem_destroy (&Bin_sem);
Because the semaphore is also a resource. When you're done with it, release.
The following is a classic example of a tutorial, dry foods as follows. Of course, you can also view the man page example.
#include <stdio.h>#include<unistd.h>#include<stdlib.h>#include<string.h>#include<pthread.h>#include<semaphore.h>void*thread_function (void*arg); sem_t Bin_sem;#defineWork_size 1024CharWork_area[work_size];intMain () {intRes; pthread_t A_thread; void*Thread_result; Res= Sem_init (&bin_sem,0,0); if(Res! =0) {perror ("Semaphore Initialization failed!\n"); Exit (Exit_failure); } Res= Pthread_create (&a_thread,null,thread_function,null); if(Res! =0) {perror ("Thread creation failed"); Exit (Exit_failure); } printf ("Input some text. Enter ' End ' to finihed"); while(STRNCMP ("End", Work_area,3) !=0) {fgets (Work_area,work_size,stdin); Sem_post (&Bin_sem); } printf ("\nwainting for Theread to finish...\n"); Res= Pthread_join (a_thread,&Thread_result); if(Res! =0) {perror ("Thread Join failed"); Exit (Exit_failure); } printf ("Thread joined\n"); Sem_destroy (&Bin_sem); Exit (exit_failure);}void*thread_function (void*Arg) {sem_wait (&Bin_sem); while(STRNCMP ("End", Work_area,3) !=0) {printf ("You input%d characters\n", strlen (Work_area)-1); Sem_wait (&Bin_sem); } pthread_exit (NULL);}
Linux Thread Sync---semaphores