pthread_attr_init,函式,作用是初始化一個執行緒對象的屬性,需要用pthread_attr_destroy函式對其去除初始化。
基本介紹
- 外文名:pthread_attr_init
- 屬性:初始化一個執行緒對象的屬性
- 頭檔案:#include<pthread.h>
- 參數:指向一個執行緒屬性的指針
簡介
頭檔案
函式聲明
返回值
參數說明
示例:創建一個脫離執行緒
#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<pthread.h>const char message[] = "Hello, Linux.";int thread_finished = 0;void thread_function(void *arg){ pthread_t newthid; newthid = pthread_self(); printf("New thread, thread ID = %lu, argument is: %s\n", newthid, (char*)arg); sleep(3); printf("New thread sets thread_finished flag and exits.\n"); thread_finished = 1; pthread_exit(NULL);}int main(int argc, char *argv[]){ int ret; pthread_t thid; pthread_attr_t attr; ret = pthread_attr_init(&attr); if(ret != 0){ printf("Error pthread_attr_init()!"); exit(EXIT_FAILURE); //執行緒屬性初始化出錯退出 } ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); if(ret != 0){ printf("Error pthread_attr_setdetachstate()!"); exit(EXIT_FAILURE); //執行緒分離屬性設定出錯退出 } //create a new thread ret = pthread_create(&thid, &attr, (void*)&thread_function, (void*)message); if(ret != 0){ printf("Error pthread_create()!"); exit(EXIT_FAILURE); } //銷毀執行緒屬性結構,它在重新初始化之前不能重新使用 pthread_attr_destroy(&attr); while(!thread_finished){ printf("Main thread, waiting for other thread finished...\n"); sleep(1); } printf("Other thread fiinshed. Bye!\n"); return 0;}