多线程编程——互斥量

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31860135/article/details/84957796
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
/* 线程控制块 */
static pthread_t tid1;
static pthread_t tid2;
/* 函数返回值检查 */
static void check_result(char* str,int result)
{
	if (0 == result)
	{
		printf("%s successfully!\n",str);
	}
	else
	{
		printf("%s failed! error code is %d\n",str,result);
	}
}
/* 互斥锁控制块 */
static pthread_mutex_t mutex;
/* 线程共享的打印函数 */
static void printer(char* str)
{
	while(*str != 0)
	{
		putchar(*str); /* 输出一个字符 */
		str++;
		sleep(1); /* 休眠1秒 */
	}
	printf("\n");
}

/*线程入口*/
static void* thread1_entry(void* parameter)
{
	char* str = "thread1 hello RT-Thread";
	while (1)
	{
		pthread_mutex_lock(&mutex); /* 互斥锁上锁 */
		printer(str); /* 访问共享打印函数 */
		pthread_mutex_unlock(&mutex); /* 访问完成后解锁 */
		sleep(2); /* 休眠2秒 */
		//printf("sleep 2s");
	}
}
static void* thread2_entry(void* parameter)
{
	char* str = "thread2 hi world";
	while (1)
	{
		pthread_mutex_lock(&mutex); /* 互斥锁上锁 */
		printer(str); /* 访问共享打印函数 */
		pthread_mutex_unlock(&mutex); /* 访问完成后解锁 */
		sleep(2); /* 休眠2秒 */
	}
}
/* 用户应用入口 */
int application_init()
{
	int result;
	/* 初始化一个互斥锁 */
	pthread_mutex_init(&mutex,NULL);
	/*创建线程1,线程入口是thread1_entry, 属性参数为NULL选择默认值,入口参数是NULL*/
	result = pthread_create(&tid1,NULL,thread1_entry,NULL);
	check_result("thread1 created",result);
	/*创建线程2,线程入口是thread2_entry, 属性参数为NULL选择默认值,入口参数是NULL*/
	result = pthread_create(&tid2,NULL,thread2_entry,NULL);
	check_result("thread2 created",result);
	return 0;
}
int main()
{
	int i ;
	application_init();
	i=100;
	do{
		sleep(1);
	}while(i--);
}

运行结果:

thread1 hello RT-Thread-bash-3.2$ gcc -pthread mutex.c -o app
-bash-3.2$ ./app
thread1 created successfully!
thread2 created successfully!
thread1 hello RT-Thread
thread2 hi world

猜你喜欢

转载自blog.csdn.net/qq_31860135/article/details/84957796
今日推荐