信号量阻塞线程实验

/*主进程创建两个线程thread1和thread2,随后等待thread2的结束。
而thread2等待thread1给信号量加1从而停止阻塞,thread1又在等待
用户输入以往下执行。所以,程序运行的效果是:首先等待用户输入
字符,用户输入字符之后thread1输出字符串,并使信号量从0变为1,
然后thread1结束。thread2停止阻塞,输出字符串。最后主进程结束。*/

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

struct sem_t
{
 long int sem1;
};
struct sem_t sem; //define a struct of semaphore

void thread1()
{
 int a;
 a=getchar();
 printf("This is the 1st thread !");
 sem_post(&sem); //semaphore adds one
}

void thread2()
{
 sem_wait(&sem); //block the present thread till semaphore is bigger than zero
 printf("This is the 2nd thread !");
}

int main()
{
 pthread_t t1,t2;
 sem_init(&sem,0,0); //initialize semaphore
 pthread_create(&t1,NULL,(void*)thread1,NULL); //create thread1
 pthread_create(&t2,NULL,(void*)thread2,NULL); //create thread2
 pthread_join(t2,NULL);
 return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值