https://www.cnblogs.com/litaoyang/p/6606499.html

信号量实现线程互斥

信号量实现线程同步

生产者消费者模型

https://keyon-photo-1256901694.cos.ap-beijing.myqcloud.com/markdown/20200512115025.png

https://keyon-photo-1256901694.cos.ap-beijing.myqcloud.com/markdown/20200512115050.png

信号量创建与初始化 sem_init

P操作 将信号量减一 sem_wait 小于0阻塞 阻塞式; 非阻塞式sem_trywait

V操作 将信号量加一 sem_post

获取信号量值 sem_getvalue

销毁信号量 sem_destroy

练习

 #include <stdio.h>
 #include <pthread.h>
 #include <errno.h>
 #include <signal.h>
 #include <unistd.h>
 #include <semaphore.h>
 #include <stdlib.h>
 ​
 sem_t sem;
 ​
 void printer(char *str) {
     sem_wait(&sem); // P操作
     while(*str) {
         putchar(*str);
         fflush(stdout);
         str++;
         sleep(1);
     }
     sem_post(&sem); // V操作
 }
 ​
 void *thread_fun1(void *arg) {
     char *str1 = "hello";
     printer(str1);
 }
 ​
 void *thread_fun2(void *arg) {
     char *str2 = "world";
     printer(str2);
 }
 ​
 ​
 int main() {
     pthread_t tid1, tid2;
 ​
     sem_init(&sem, 0, 1);
     pthread_create(&tid1, NULL, thread_fun1, NULL);
     pthread_create(&tid2, NULL, thread_fun2, NULL);
 ​
     pthread_join(tid1, NULL);
     pthread_join(tid2, NULL);
     return 0;
 }