C/C++ 多線程

Linux:

編譯gcc:  連接線程庫 -lpthread

#include<pthread.h>

void* Function(void* pf) {
  return NULL;
}

int main(int argc, char *argv[]) {
  pthread_t thread_id;
  pthread_create(&thread_id, NULL, &Function, arg);
  pthread_join(thread_id ,NULL);
  return 0;
}

pthread_create 創建一個線程,參數分別表示: (線程ID,設置線程屬性,函數指針void*(*pFunc)(void*),線程參數void* arg) 返回值爲0表示成功。

pthread_join 以阻塞的方式等待線程結束,參數表示:(線程ID,返回值void **retval)。

注意:一個線程不能被多個線程等待,否則第一個接收到信號的線程成功返回,其餘調用pthread_join的線程則返回錯誤代碼ESRCH。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章