LINUX学习之 只用互斥锁实现两个进程同步

 程序功能:

A线程进行从1到100的累加,累加结果放在全局变量C中。

B线程根据A的实时运算结果,检测到累加值可以 被10整除时马上输出此时的C值。


程序思路:

设置一个全局变量F ,县城B通过检测F的值来判断是否输出当前C值,线程A通过检测F的值来判断是否继续累加,达到线程同步的效果。

在AB线程分别判断F值的语句前后加上P操作和V操作,也就是加锁和释放锁,来达到线程互斥。


程序代码:

#include<pthread.h>
#include<stdio.h>
int  c=0;
int f=0;
pthread_mutex_t t;
void f1(void *arg)
{
   int i=1;
   while(i<=40)
	{
pthread_mutex_lock(&t);
	if(f==0)
      {	
	c+=i;
	i++;
	printf("%d   \n",c);
	if(c%10==0)
	{
	 f=1;
	
	}
      }
pthread_mutex_unlock(&t);
	}

}
void f2(void *arg)
{
    while(1)
	{
		if(f==1)
		{
		pthread_mutex_lock(&t);
		f=0;
		printf("-------%d   \n",c);
		pthread_mutex_unlock(&t);
		
		}
}


}
int main()
{
pthread_t a;
pthread_t b;
pthread_mutex_init(&t,NULL);
pthread_create(&a,NULL,f1,NULL);

pthread_create(&b,NULL,f2,NULL);

pthread_join(a,0);
pthread_join(b,0);



}







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值