簡體   English   中英

為什么我需要從主線程使用 `pthread_exit()`,而它不是由 `pthread_create` 創建的?

[英]Why do I need to use `pthread_exit()` from the main thread, while it was not created by a `pthread_create`?

我對一些我正在測試以開始理解 posix 線程的代碼有疑問。

我有這個基本代碼:

#include <iostream>
#include <string>
#include <sstream>
#include <pthread.h>

using namespace std;

void *printInfo(void *thid){
    long tid;
    tid =(long)thid;
    printf("Hello from thread %ld.\n",tid);
    pthread_exit(NULL);
}

int main (int argc, char const *argv[])
{
    int num =8;
    pthread_t threadlist[num];
    int rc;
    long t;
    for(t=0;t<num;t++){
        printf("Starting thread %ld\n",t);
        rc = pthread_create(&threadlist[t],NULL,printInfo,(void *)t);
        if(rc)
        {
            printf("Error creating thread");
            exit(-1);
            
        }
    }
    pthread_exit(NULL);
    return 0;
}

非常簡單的代碼,啟動線程並從中打印,這一切都很神奇,除了我不明白return 0;之前的最后一個pthread_exit(NULL) return 0; 在 main 方法的最后。

似乎主線程不應該是 pthread,而且應該不需要! 如果我不放它,代碼就不起作用:代碼編譯並執行,但我只得到“起始線程”打印消息,而不是“hello from ...”消息。

所以基本上我想知道為什么需要這樣做。

此外,如果我注釋掉 include <psthread.h> ,代碼會編譯並正確執行。

如果您不在主函數中使用 pthread_exit,那么所有創建的線程都將在主完成時終止,即在您的情況下,在它們打印任何內容之前。

通過在 main 函數中調用 pthread_exit 使 main 等待所有線程完成。

從 pthread_exit 手冊頁:

在最后一個線程終止后,進程將以退出狀態 0 退出。 行為就像實現調用 exit() 在線程終止時參數為零一樣。

這是指從主進程線程調用 pthread_exit()。

pthread_exit只會終止主線程,但會讓其他線程運行直到它們完成它們的工作。 而如果您從main返回或調用exit ,這將強制終止所有線程。

你需要加入你的線程。 沒有pthread_exit的情況是您已經啟動了線程,然后 main 在它實際運行任何線程之前退出。 當 main 退出時,程序停止運行(線程也是如此)。

通常,您會使用pthread_join等待指定的線程完成執行。

似乎pthread_exit導致 main 等待我不知道的所有線程。 但是,我會研究一下,因為它不在文檔中(就我所閱讀的而言),並且可能不是您想要依賴的東西。

編輯:同樣在您的情況下,您根本不需要使用pthread_exit 當執行的函數(在您的情況下為printInfo )返回時,線程將自動終止。 pthread_exit允許您在執行的函數返回之前終止線程,例如,如果執行的函數調用另一個調用pthread_exit函數。

暫無
暫無

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

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