linux c 线程同步之信号量 semaphores 入门之二

步骤:

初始化信号量: sem_init,设置默认信号量的值,我们下面设置为0
等待:sem_wait() 如果信号量大于0,则将信号量减一,返回成功,
如果信号量等于0,则阻塞一直等信号量大于0.

增加信号量: sem_post 加一。唤醒等待的线程。

我们下面的场景是这样的:
初始信号量为0,先启动2个线程等待这个信号量,由于为0,则被阻塞,
在另外一个线程再延迟3秒发送post,则随机唤醒前面的2个线程中的一个。

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

/**
 *https://man7.org/linux/man-pages/man7/sem_overview.7.html
 * https://www.geeksforgeeks.org/pthread_self-c-example/
 */

sem_t sem;

void* calls(void *ptr) {
	printf("sem_wait\n");
	sem_wait(&sem);
	printf("continue run now\n");
	return NULL;
}

void* calls3(void *ptr) {
	sleep(3);
	printf("post now\n");
	sem_post(&sem);
	sleep(3);
	printf("post now\n");
	sem_post(&sem);
	return NULL;
}

int main() {
	if (sem_init(&sem, 0, 0) == -1) {
		exit(EXIT_FAILURE);
	}

	pthread_t thread;
	pthread_t thread2;
	pthread_t thread3;
	pthread_create(&thread, NULL, calls, NULL);
	pthread_create(&thread2, NULL, calls, NULL);
	pthread_create(&thread3, NULL, calls3, NULL);
	pthread_join(thread, NULL);
	pthread_join(thread2, NULL);
	pthread_join(thread3, NULL);
	sem_destroy(&sem);
	printf("main exit\n");
	return EXIT_SUCCESS;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值