簡體   English   中英

關於pthread_join()和pthread_detach()的問題

[英]question on pthread_join() and pthread_detach()

我寫了這個程序來練習pthread系統調用,所以我用了一些打印行來檢查結果,但是它們被轉義了,輸出是:

Thread 1 created Thread 2 created test3

雖然我認為應該

thread 1 created test2 thread 2 created test3 test1順序可能會改變,但是我應該有這行內容,所以為什么要轉義此打印語句?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>



void *function();
void *function2();




int main(int argc, char *argv[])
{
    pthread_t tid;
    int rc;
    rc = pthread_create(&tid, NULL, function(), NULL);
    if(rc > 0){
        fprintf(stderr, "Error\n");
        exit(1);
    }
    pthread_join(tid, NULL);
    sleep(1);
    printf("test1\n");
    pthread_exit(NULL);
}

void *function(){
    int rc;
    pthread_t tid;
    printf("Thread 1 created\n");
    rc = pthread_create(&tid, NULL, function2(), NULL);
    if(rc > 0){
        fprintf(stderr, "Error\n");
        exit(1);
    }
    printf("test2\n");
    pthread_exit(NULL);
}

void *function2(){
    pthread_detach(pthread_self());
    printf("Thread 2 created\n");
    printf("test3\n");
    pthread_exit(NULL);
}
rc = pthread_create(&tid, NULL, function(), NULL);

您嘗試使用通過調用function()返回的指針來調用pthread_create()作為要在新線程中運行的函數(請記住,在調用函數本身之前先對函數參數進行評估)。 現在, function()實際上並不返回任何值,但它調用function2()在它的身上(而評估的參數再調用pthread_create()不會返回任何值,但確實調用pthread_exit() 由於此時只有一個線程,因為僅在運行主進程線程( pthread_create()尚未真正被調用;因此調用堆棧看起來像main() -> function() -> function2() ),整個程序然后退出。

您需要使用指向functionfunction2指針來調用pthread_create() ,而不是調用它們的結果:

rc = pthread_create(&tid, NULL, function, NULL);

等等

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM