2017-10-10 144 views
0

我有一個Linux的C應用程序中的pthread庫的問題。C與Pthread崩潰的應用程序

在我的應用程序中,線程一遍又一遍地重新啓動。 但我總是等到線程完成之後再啓動它。

在某些時候,線程不會再啓動,並且出現內存不足錯誤。

我發現的解決方案是在線程完成後執行pthread_join。

誰能告訴我爲什麼線程不能正確結束?

以下是導致相同問題的示例代碼。 如果在pthread_join不叫進程停在約380調用Thread的:

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

volatile uint8_t check_p1 = 0; 
uint32_t stack_start; 

void *thread1(void *ch) 
{ 
    static int counter = 0; 
    int i; 
    int s[100000]; 
    char stack_end; 
    srand(time(NULL) + counter); 
    for (i = 0; i < (sizeof (s)/sizeof(int)); i++) //do something 
    { 
    s[i] = rand(); 
    } 
    counter++; 
    printf("Thread %i finished. Stacksize: %u\n", counter, ((uint32_t) (stack_start)-(uint32_t) (&stack_end))); 

    check_p1 = 1; // Mark Thread as finished 
    return 0; 
} 

int main(int argc, char *argv[]) 
{ 
    pthread_t p1; 
    int counter = 0; 
    stack_start = (uint32_t)&counter; // save the Address of counter 
    while (1) 
    { 
    counter++; 
    check_p1 = 0; 
    printf("Start Thread %i\n", counter); 
    pthread_create(&p1, NULL, thread1, 0); 
    while (!check_p1) // wait until thread has finished 
    { 
     usleep(100); 
    } 
    usleep(1000); // wait a little bit to be really sure that the thread is finished 
    //pthread_join(p1,0); // crash without pthread_join 

    } 
    return 0; 
} 
+0

未定義行爲不同步,非只讀,非原子訪問來自多個對象線程。 – EOF

回答

0

我找到解決的辦法是做一個在pthread_join的線程完成之後。

這就是正確的解決方案。你必須這樣做,否則你泄露線程資源。

誰能告訴我爲什麼線程不能正確結束?

確實末正確的,但你必須加入它,以使線程庫知道:「是的,他確實是這個線程中完成的,沒有必要持有資源不再」。

這是正是同樣的原因,你必須在這個循環使用wait(或waitpid等):

while (1) { 
    int status; 
    pid_t p = fork(); 
    if (p == 0) exit(0); // child 
    // parent 
    wait(&status); // without this wait, you will run out of OS resources. 
}