”多线程+信号量+互斥锁“ 亲测可用的简单demo

信号量不是信号。

信号量的使用:

头文件  <semaphore.h>

定义信号量  sem_t sem;

初始化  sem_init(&sem);

等待信号量  sem_wait(&sem);

发送信号量  sem_post(&sem);

销毁信号量  sem_destroy(&sem);

/*requirment: pthread0 prints string before pthread1
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

pthread_mutex_t mutex;
sem_t sem;
int source=10;
void pthread0(void)
{
    while(1)
    {
	pthread_mutex_lock(&mutex);
	source=0;
	pthread_mutex_unlock(&mutex);
	printf("this is thread0 and the source is %d\n",source);
	sem_post(&sem);
	sleep(2);
    }
}
void pthread1(void)
{
    while(1)
    {
	sem_wait(&sem);
	pthread_mutex_lock(&mutex);
	source=1;
	pthread_mutex_unlock(&mutex);
	printf("this is thread1 and the source is %d\n",source);
	sleep(2);
    }
}

void main()
{
    pthread_t id0;
    pthread_t id1;
    sem_init(&sem,0,0);
    pthread_mutex_init(&mutex,NULL);
    pthread_create(&id0,NULL,(void*)pthread0,NULL);
    pthread_create(&id1,NULL,(void*)pthread1,NULL);
    while(1)
    {
	printf("this is main function\n");
	sleep(2);
    }
    pthread_join(id0,NULL);
    pthread_join(id1,NULL);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值