2017-10-10 148 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. 
}