多线程编程——创建线程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31860135/article/details/84957420
#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 void* thread_entry(void* parameter)
{
	int count = 0;
	int no = (int) parameter; /* 获得线程的入口参数 */
	pthread_detach(pthread_self());
	while (1)
	{
		/* 打印输出线程计数值 */
		printf("thread%d count: %d\n", no, count ++);
		sleep(2); /* 休眠2秒 */
	}
}
/* 用户应用入口 */
int application_init()
{
	int result;
	/* 创建线程1, 属性为默认值,入口函数是thread_entry,入口函数参数是1 */
	result = pthread_create(&tid1,NULL,thread_entry,(void*)1);
	check_result("thread1 created", result);
	/* 创建线程2, 属性为默认值,入口函数是thread_entry,入口函数参数是2 */
	result = pthread_create(&tid2,NULL,thread_entry,(void*)2);
	check_result("thread2 created", result);
	return 0;
}
int main()
{
	int i ;
	application_init();
	i=5;
	do{
		sleep(1);
	}while(i--);
}

运行结果:

thread1 created successfully!
thread1 count: 0
thread2 created successfully!
thread2 count: 0
thread1 count: 1
thread2 count: 1
thread1 count: 2
thread2 count: 2
thread1 count: 3
thread2 count: 3

thread1 created successfully!
thread2 created successfully!
thread1 count: 0
thread2 count: 0
thread1 count: 1
thread2 count: 1
thread1 count: 2
thread2 count: 2
thread1 count: 3
thread2 count: 3

猜你喜欢

转载自blog.csdn.net/qq_31860135/article/details/84957420