2月6日作业

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

#include 
int num = 500;
pthread_mutex_t mutex;
void *task1(void *arg)
{
	while(1)
	{
		sleep(1);
		pthread_mutex_lock(&mutex);
		num--;
		printf("num1:%d\n",num);
		pthread_mutex_unlock(&mutex);
	}
	pthread_exit(NULL);
}
void *task2(void *arg)
{
	while(1)
	{
		sleep(1);
		pthread_mutex_lock(&mutex);
		num--;
		printf("num2:%d\n",num);
		pthread_mutex_unlock(&mutex);
	}
	pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
	pthread_t tid1,tid2;
	pthread_mutex_init(&mutex,NULL);
	if(pthread_create(&tid1,NULL,task1,NULL) != 0)
	{
		fprintf(stderr,"pthread_create1 error\n");
		return -1;
	}
	if(pthread_create(&tid2,NULL,task2,NULL) != 0)
	{
		fprintf(stderr,"pthread_create2 error\n");
		return -1;
	}
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);
	pthread_mutex_destroy(&mutex);
	return 0;
}

效果演示

2月6日作业_第1张图片

你可能感兴趣的:(前端)