两个线程实现同步代码示例

#include
 
//1、定义无名信号量
sem_t sem;
 
//定义生产者线程
void *task1(void *arg)
{
	int num = 5;
	while(num--)
	{
		sleep(1);
		printf("我生产了一辆汽车\n");
 
		//4、释放资源
		sem_post(&sem);
	}
 
	//退出线程
	pthread_exit(NULL);
}
 
 
//定义消费者线程
void *task2(void *arg)
{
	int num = 5;
	while(num--)
	{
		//sleep(1);
 
		//3、申请资源
		sem_wait(&sem);
 
		printf("我购买了一辆汽车\n");
	}
 
	//退出线程
	pthread_exit(NULL);
}
 
 
 
int main(int argc, const char *argv[])
{
	//定义两个线程号
	pthread_t tid1, tid2;
 
	//2、初始化无名信号量
	sem_init(&sem, 0, 0);
	//第一个0表示线程间同步
	//第二个0表示初始资源为0
 
 
	//创建两个线程
	if(pthread_create(&tid1, NULL, task1, NULL) != 0)
	{
		printf("tid1 create error\n");
		return -1;
	}
 
	//创建两个线程
	if(pthread_create(&tid2, NULL, task2, NULL) != 0)
	{
		printf("tid2 create error\n");
		return -1;
	}
 
	printf("tid1 = %#lx, tid2 = %#lx\n", tid1, tid2);
 
	//回收线程资源
	pthread_join(tid1 , NULL);
	pthread_join(tid2 , NULL);
 
	//5、销毁无名信号量
	sem_destroy(&sem);
 
	return 0;
}

两个线程实现同步代码示例_第1张图片

你可能感兴趣的:(java,开发语言)