天天看點

POSIX建立終止線程建立線程終止線程線程範例

本文參考《嵌入式Linux開發教程》和《Linux/UNIX系統程式設計手冊》。

建立線程

thread 用來指向新建立線程的 ID;

attr 用來表示一個封裝了線程各種屬性的屬性對象,如果 attr 為 NULL,新線程就使用預設的屬性;

start_routine 是線程開始執行的時候調用的函數的名字;

arg 為參數 start_routine 指定函數的參數。

終止線程

程序的終止可以通過直接調用 exit()、執行 main()中的 return、或者通過程序的某個其它線程調用 exit()來實作。在以上任何一種情況發生時,所有的線程都會被終止。如果主線程在建立了其它線程後沒有任務需要處理,那麼它應該阻塞等待直到所有線程都結束為止,或者應該調用 pthread_exit(NULL)。

調用 exit()函數會使整個程序終止,而調用 pthread_exit()隻會使得調用線程終止,同時在建立的線程的頂層執行 return 線程會隐式地調用 pthread_exit()。

retval 是一個 void 類型的指針,可以将線程的傳回值當作 pthread_exit()的參數傳入,這個值同樣被 pthread_join()當作退出狀态處理。如果程序的最後一個線程調用了 pthread_exit(),程序會帶着狀态傳回值 0 退出。

線程範例

主線程建立了 5 個線程,這 5 個線程和主線程并發執行,主線程建立完線程後調用 pthread_exit()函數退出線程,其它線程分别

列印目前線程的序号。當主線程先于其它程序執行 pthread_exit()時,程序還不會退出,隻有最後一個線程也完成了,程序才會退出。

[email protected]-virtual-machine:~/workspace/test$ cat sample.c 
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS     5

void *PrintHello(void *threadid){	//線程函數
   long tid;
   tid = (long)threadid;
   printf("Hello World! It's me, thread #%ld!\n", tid);	//列印線程對應的參數
   pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc;
   long t;
   for(t=0; t<NUM_THREADS; t++){	//循環建立5個線程
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);	//建立線程
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }
   }
   printf("In main: exit!\n");
   pthread_exit(NULL);	//主線程退出
}

           

下面為運作結果,程式中主線程調用了 pthread_exit()函數并不會将整個程序終止,而是當最後一個線程調用 pthread_exit()時程式才完成運作。

[email protected]-virtual-machine:~/workspace/test$ gcc sample.c -o sample -[email protected]-virtual-machine:~/workspace/test$ ./sample
In main: creating thread 0
In main: creating thread 1
Hello World! It's me, thread #0!
Hello World! It's me, thread #1!
In main: creating thread 2
In main: creating thread 3
Hello World! It's me, thread #2!
In main: creating thread 4
Hello World! It's me, thread #3!
In main: exit!
Hello World! It's me, thread #4!
[email protected]-virtual-machine:~/workspace/test$ 
           

繼續閱讀