Linux編程:互斥鎖實現共享資源訪問

使用互斥鎖實現共享資源訪問 

能打印完整的hello world或者HELLO WORLD, 而不是hello和world分離

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_mutex_t m;//定義互斥鎖
 void err_thread(int ret,char *str)
{
	if(ret!=0)
	{
		fprintf(stderr,"%s:%s\n",str,strerror(ret));
		pthread_exit(NULL);
	}
}
void *tfn(void *arg)
{
	srand(time(NULL));
	while(1)
	{
		//加鎖 m--
		pthread_mutex_lock(&m);
		printf("hello");
		printf("world!\n");
		//解鎖 m++
		pthread_mutex_unlock(&m);
		sleep(rand()%3);	
	}
	return NULL;
}

int main(void)
{
	pthread_t tid;
	srand(time(NULL));
	int flag=5;
	//初始化mutex
	pthread_mutex_init(&m,NULL);
	//創建線程
	int ret = pthread_create(&tid,NULL,tfn,NULL);
	err_thread(ret,"pthread_create error");

	while(flag--)
	{
		//加鎖 m--
		pthread_mutex_lock(&m);
		printf("HELLO");
		printf("WORLD!\n");
		//解鎖 m++
		pthread_mutex_unlock(&m);
		sleep(rand()%3);
	}

	//取消線程
	pthread_cancel(tid);
	//等待線程終止
	pthread_join(tid,NULL);
	//銷燬鎖
	pthread_mutex_destroy(&m);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章