有名信号量与无名信号量以及信号灯

无名信号量

1.相关函数

    #include <semaphore.h>

	int sem_init(sem_t *sem, int pshared, unsigned int value);
	//sem:初始化的信号量
	//pshared:信号量共享的范围(0:线程间使用,非0:进程间使用)
	//value:信号量初值。
	   #include <semaphore.h>

       int sem_wait(sem_t *sem);
       /*P操作
      	if(信号量的值大于0){申请资源的任务继续进行,信号量的值减一}
      	else{申请资源的任务阻塞} */
	   #include <semaphore.h>

       int sem_post(sem_t *sem);

       Link with -pthread.
       /*V操作
       if(没有任务在等待该资源){信号量的值加一}
       else{唤醒第一个等待的任务,让其继续运行}*/

2.作用

只能用于线程中的同步,当赋值为0/1时可实现互斥

3.注意

这里为什么只能用于线程中?
原因:因为在父子进程中虽然子进程会copy父进程的内容,但调用sem_init后,两者的信号量并不是同一个地址进行操作,所以并不能实现进程中的同步。

4.代码段

实现三个线程的输出顺序固定,并且同步输出

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
sem_t sem1,sem2,sem3;

//定义线程需要执行的函数

void *threadFunc1(void *arg)
{
   
	while(1)
	{
   
		sem_wait(&sem1);
		sleep(1);
		printf("采集图片...\n");
		sem_post(&sem2);
	}
}
void *threadFunc2(void *arg)
{
   
	while(1)
	{
   
		sem_wait(&sem2);
		printf("处理图片...\n");
		sem_post(&sem3);
	}
}
void *threadFunc3(void *arg)
{
   
	while(1)
	{
   
		sem_wait(&sem3);
		printf("发送图片...\n");
		printf("----------\n");
		sem_post(&sem1);
	}

}
int main()
{
   
	//初始化信号量
	sem_init(&sem1,0,1);
	sem_init(&sem2,0,0);
	sem_init(&sem3,0,0);

	//创建线程
	pthread_t pthread1,pthread2,pthread3;
	pthread_create(&pthread1,NULL,threadFunc1,NULL);
	pthread_create(&pthread2,NULL,threadFunc2,NULL);
	pthread_create(&pthread3,NULL,threadFunc3,NULL);

	//等待进程结束
	pthread_join(pthread1, NULL);
	pthread_join(pthread2, NULL);
	pthread_join(pthread3, NULL);

	return 0;
}

5.结果展示

采集图片...
处理图片...
发送图片...
----------
采集图片...
处理图片...
发送图片...
----------

有名信号量

1.相关函数

       
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值