Linux C编程进行线程的同步

时间:2021-02-12 11:01:05

今天学习了用Linux C进行线程的同步,实现类似生产者消费者的问题。下面我就来分享我的代码

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


pthread_t tid1;
pthread_t tid2;
pthread_cond_t cond_id;
pthread_mutex_t  mutex_id;
int number = 0;
int i = 0;

void * thread_printA()
{
	while(i<100)
	{
		pthread_mutex_lock(&mutex_id);
		if(number<0)
		{
			pthread_cond_wait(&cond_id,&mutex_id);
		}
		number--;
		printf("A");
		i++;
	
		pthread_cond_signal(&cond_id);
		pthread_mutex_unlock(&mutex_id);
	}
}

void * thread_printB()
{
	while(i<100)
	{
		pthread_mutex_lock(&mutex_id);
		if(number>=0)
		{
			pthread_cond_wait(&cond_id,&mutex_id);
		}
		number++;
		printf("B");
		i++;
		pthread_cond_signal(&cond_id);
		pthread_mutex_unlock(&mutex_id);
	}
}

void main()
{
	pthread_create(&tid1,NULL,thread_printA,NULL);
	pthread_create(&tid2,NULL,thread_printB,NULL);
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);
}