當 thread 設定 PTHREAD_CREATE_DETACHED 屬性時,thread 執行結束時不會保留返回值,會直接釋放所有資源並結束。當使用 pthread_join 一個 PTHREAD_CREATE_DETACHED 屬性的執行緒,會返回錯誤值,而且也得不到返回值。

#include <pthread.h> #include <stdio.h> #include <unistd.h> void* thread_func(void *param) { int i=0; int *running = (int*)param; printf("[%s:%d,%s]thread start\n", __FILE__, __LINE__, __func__); while(*running) { printf("[%s:%d,%s]%d\n", __FILE__, __LINE__, __func__, i++); sleep(1); } printf("[%s:%d,%s]thread stop\n", __FILE__, __LINE__, __func__); return (void*)123; } int main(int argc, char **argv) { void *return_value=0; int running; pthread_t thrid; pthread_attr_t attr; running = 1; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&thrid, &attr, thread_func, (void*)&running); pthread_attr_destroy(&attr); sleep(5); running = 0; pthread_join(thrid, &return_value); printf("[%s:%d,%s]%d\n", __FILE__, __LINE__, __func__, (int)return_value); sleep(1); return 0; } # ./a.out [test.cpp:9,thread_func]thread start [test.cpp:11,thread_func]0 [test.cpp:11,thread_func]1 [test.cpp:11,thread_func]2 [test.cpp:11,thread_func]3 [test.cpp:11,thread_func]4 [test.cpp:32,main]0 [test.cpp:14,thread_func]thread stop

台南小新 發表在 痞客邦 PIXNET 留言(0) 人氣()