信号量在线程同步中的使用与在进程同步中类似。
信号量可以理解为是一个全局的非负整数计数器,使用过程无非是:初始化->P/V操作->销毁。相关的函数分别为:sem_init、sem_wait、sem_post、sem_destory,包含在头文件semapore.h中。
-
int sem_init (sem_t *__sem, int __pshared, unsigned int __value)
_sem:要初始化的信号量;_pshared:指明由进程还是线程共享;_value:信号量初始值
-
sem_wait:P操作
int sem_destroy (sem_t *__sem)
信号量的值为0则阻塞当前线程,不为零则将值减1.
P操作
3.sem_post:V操作,函数声明同sem_wait、sem_destory
若没有线程因为此信号阻塞则将信号值加1,若有则解除阻塞。
V操作
4.例程:例程代码分享在码云上,有兴趣的自取,链接放在百度脑图了。
脑图: naotu.baidu.com/file/6eaa2ea4127765f8005713238ad0e7b3?token=99b15a229f4da73d 密码: jqsj
#include<pthread.h>
#include<semaphore.h>
#include<stdlib.h>
#include<errno.h>
#include<stdio.h>
#include<unistd.h>
#define Max 100
static sem_t sem1,sem2;
static int global=1;
void *t1_exe(void *arg){
while(global<Max){
sem_wait(&sem1);
printf("thread 1 before increment global=%d\n",global);
global++;
printf("thread 1 after increment global=%d\n",global);
sem_post(&sem2);
sleep(1);
}
}
void *t2_exe(void *arg){
while(global<Max){
sem_wait(&sem2);
printf("thread 2 before increment global=%d\n",global);
global++;
printf("thread 2 after increment global=%d\n",global);
sem_post(&sem1);
sleep(2);
}
}
int main(){
pthread_t pid1,pid2;
int error1,error2;
if(sem_init(&sem1,0,1)/*==-1*/||sem_init(&sem2,0,0)==-1){
perror("sem initialized failed\n");
exit(0);
}
error1=pthread_create(&pid1,NULL,t1_exe,NULL);
error2=pthread_create(&pid2,NULL,t2_exe,NULL);
if(error1!=0||error2!=0){
printf("thread create failed\n");
return 1;
}
pthread_join(pid1,NULL);
pthread_join(pid2,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
getchar();
return 0;
}