1. 程式人生 > >linux執行緒建立和銷燬

linux執行緒建立和銷燬

基本函式介紹

建立執行緒

int ptread_create(pthread_t *thread, 
    const pthread_att_t *attr,
    void * (*start)(void *),
    void *arg)
  • 返回值
  • 引數
    • thread
      pthread_t 型別的緩衝區,在建立函式返回前,會在此儲存一個該執行緒的唯一標識。
    • attr
      執行緒屬性,後續其他文章介紹,很多時候,直接用 NULL就能滿足需求
    • start
      指向執行緒入口函式的指標,這個指標指向一個函式,這個函式的返回值時一個指標,引數也是一個指標。在應用執行緒取消技術的時候,不建議返回強制轉換後的整型,因為取消執行緒的返回值 PTHREAD_CANCELED 一般也會時整型值,兩個值有可能相同,可能會出現問題。
    • arg
      start函式的引數,一般指向一個全域性或者堆變數,如果要傳遞多個引數,可以考慮把引數封裝在一個結構體裡面

終止執行緒

可以使用如下方式終止執行緒執行

  • start函式執行return語句並返回指定值
  • 執行緒呼叫 pthread_exit() 函式,和retrun不同地方是,在start函式所呼叫的任何函式中,呼叫 pthread_exit()都會終止執行緒
  • 呼叫pthread_cance()取消執行緒
  • 任何執行緒呼叫了exit()或者主執行緒執行了return語句,都會導致所有執行緒終止
void pthread_exit(void *retval)
  • retval
    執行緒的返回值,它所指向的內容不應該屬於執行緒棧,因為執行緒返回之後,執行緒棧就銷燬了

連線執行緒

對於未分離的執行緒,如果不執行 join,那麼會形成殭屍執行緒

程式碼示例

#include "cstdio"
#include "pthread.h"
static void * thread_func(void *arg)
{
    int thread_name = *(int *)arg;
    pthread_t thread_id = pthread_self();
    printf ("[thread_name:%d][thread_id:%ld]\n",thread_name, (long)thread_id);
    return
NULL; } int main() { pthread_t thread_array[10]; for (int i = 0;i < 10; i++) { int s = pthread_create(&thread_array[i], NULL, thread_func, &i); if (s != 0) { printf ("[create thread: %d error]\n", i); return -1; } } printf("[main thread]\n"); for (int i = 0;i < 10; i++) { int s = pthread_join(thread_array[i], NULL); if (s != 0) { printf("[join thread: %d error]\n", i); return -1; } } return 0; }