Linux系统编程之pthread多线程与互斥编程

Linux系统编程之pthread多线程与互斥编程


#include 
#include 
#include 
#include 

int count = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;		// 静态初始化

void* thd_print(void* arg)
{
	while(1)
	{
		pthread_mutex_lock(&mutex);

		count++;
		printf("%s : count = %d \r\n", (char *)arg, count);
		if(count > 5)
		{
			pthread_mutex_unlock(&mutex);
			break;
		}

		pthread_mutex_unlock(&mutex);
		usleep(300 * 1000);
	}

	return NULL;
}

int main(void)
{
	pthread_t pid[2];
	char* thdname[] = {"thread1", "thread2"};

	// 创建线程
	pthread_create(&pid[0], NULL, thd_print, thdname[0]);
	pthread_create(&pid[1], NULL, thd_print, thdname[1]);

	// 等待线程退出回收资源
	pthread_join(pid[0], NULL);
	pthread_join(pid[1], NULL);

	printf("Hello World \r\n");

	return 0;
}

你可能感兴趣的:(Linux,linux,互斥锁,c语言,Unix环境高级编程,pthread)