簡體   English   中英

線程終止問題(C編程)

[英]thread termination issue (c programming)

我正在使用C使用多個線程的Linux應用程序。 main函數產生的線程完成了大部分工作,因此通常最后完成。 我看到了一些奇怪的行為,並且我相信這是由於主線程在生成的線程有機會完成其工作之前終止。 這是一些示例代碼來說明我在說什么:

#define _POSIX_C_SOURCE 200112L
#define _ISOC99_SOURCE
#define __EXTENSIONS__
#define _GNU_SOURCE

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

void
my_cleanup(void *arg)
{
     printf("cleanup: %s\n", (char *)arg);
}


void *
thread_stuff(void *arg)
{
     printf("thread started\n");
     pthread_cleanup_push(cleanup, "running");
     if (arg)
          pthread_exit((void *)2);
     pthread_cleanup_pop(0);
     pthread_exit((void *)2);
}


int
main()
{
     int err;
     pthread_t tid1, tid2;

     err = pthread_create(&tid1, NULL, thread_stuff, (void *)1);
     err = pthread_create(&tid2, NULL, thread_stuff, (void *)1);

     sleep(10);                 /* change the value here if you want */

     return SUCCESS;
}

運行此代碼時,清理函數中的消息應按應有的方式打印兩次,但是有時運行時,我看到的消息有時僅打印一次,而有時我看到的消息卻打印了三遍。所有。 您可以在main函數中添加sleep函數,以播放main函數終止所需的時間。

我怎樣做才能使程序正常運行? 我懷疑這與加入孩子有關,但我並不完全了解加入的概念或如何將其應用於這種情況。

提前致謝!

是的,您應該“加入”線程。 “加入”線程僅意味着等待直到線程終止。 換句話說,你會做

pthread_join(tid1, NULL);
pthread_join(tid2, NULL);

等待兩個線程都終止。

編輯:如果您有一個子線程,又創建了一個“孫子”線程,該怎么辦? 通常,創建線程的任何人都應等待線程終止(“加入”線程)。 因此,在這種情況下,子線程將在孫線程上調用phtread_join,而主線程將在子線程上調用join。

我認為您想在主線程完成時在每個線程上運行pthread_join ,這會使主線程停止直到給定線程完成運行。 但是其他線程仍然可以先完成,因此在每個線程上運行pthread_join將阻止主線程終止,直到所有其他線程都終止。

如果main()在未顯式調用pthread_exit()的情況下在其產生的線程之前完成,則肯定存在問題。 它創建的所有線程將終止,因為main()已完成,並且不再存在以支持線程。

通過讓main()顯式調用pthread_exit()作為最后一件事,main()將被阻塞並保持活動狀態以支持它創建的線程,直到完成。

int main()
    {
         int err;
         pthread_t tid1, tid2;

         err = pthread_create(&tid1, NULL, thread_stuff, (void *)1);
         err = pthread_create(&tid2, NULL, thread_stuff, (void *)1);

         sleep(10);                 /* change the value here if you want */

         /* Add the pthread_exit */     
         pthread_exit(NULL);
         return SUCCESS;
    }

在這里參考更多信息

暫無
暫無

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

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