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

时间:2021-09-12 15:33:07

 程序功能:

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);



}