多執行緒程式設計——執行緒連線join
阿新 • • 發佈:2018-12-29
#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); } } /* 執行緒1入口函式 */ static void* thread1_entry(void* parameter) { int i; for (i = 0;i < 3;i++) /* 迴圈列印3次資訊 */ { printf("thread1 run count: %d\n",i); sleep(2); /* 休眠2秒 */ } printf("thread1 exited!\n"); return NULL; } /* 執行緒2入口函式*/ static void* thread2_entry(void* parameter) { int count = 0; void* thread1_return_value; /* 阻塞等待執行緒1執行結束 */ pthread_join(tid1, NULL); /* 執行緒2列印資訊開始輸出 */ while(1) { /* 列印執行緒計數值輸出 */ printf("thread2 run count: %d\n",count ++); sleep(2); /* 休眠2秒 */ } return NULL; } /* 使用者應用入口 */ int application_init() { int result; /* 建立執行緒1,屬性為預設值,分離狀態為預設值joinable, * 入口函式是thread1_entry,入口函式引數為NULL */ result = pthread_create(&tid1,NULL,thread1_entry,NULL); check_result("thread1 created",result); /* 建立執行緒2,屬性為預設值,分離狀態為預設值joinable, * 入口函式是thread2_entry,入口函式引數為NULL */ result = pthread_create(&tid2,NULL,thread2_entry,NULL); check_result("thread2 created",result); return 0; } int main() { int i ; application_init(); i=10; do{ sleep(1); }while(i--); }
執行結果:
-bash-3.2$ gcc join.c -pthread -o app
-bash-3.2$ ./app
thread1 created successfully!
thread2 created successfully!
thread1 run count: 0
thread1 run count: 1
thread1 run count: 2
thread1 exited!
thread2 run count: 0
thread2 run count: 1
thread2 run count: 2