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;
}
未定义行为不同步,非只读,非原子访问来自多个对象线程。 – EOF