C应用程序与Pthread崩溃

时间:2017-10-10 13:59:18

标签: pthreads

我在C-Application for Linux中遇到了pthread库的问题。

在我的应用程序中,线程一次又一次地启动。 但是我总是等到线程完成才启动它。

在某些时候线程不再启动,我得到内存不足错误。

我找到的解决方案是在线程完成后执行pthread_join。

谁能告诉我为什么线程没有正确结束?

这是一个示例代码,导致相同的问题。 如果没有调用pthread_join,则进程在大约380次线程调用时停止:

#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;
}

1 个答案:

答案 0 :(得分:0)

  

我找到的解决方案是在线程完成后执行pthread_join。

这是正确的解决方案。 必须这样做,否则会泄漏线程资源。

  

谁能告诉我为什么Thread没有正确结束?

正确结束,但你必须加入它才能让线程库知道:“是的,他真的完成了这个线程;没有必要持有资源“。

完全与您在此循环中必须使用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.
}