1. 程式人生 > >多執行緒程式設計——建立執行緒

多執行緒程式設計——建立執行緒

#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