我有以下代码。构建应用程序是 myprogram。
如果我启动 myprogram 然后 killall myprogram 然后我再次启动 myprogram 然后 myprogram 崩溃。
崩溃的原因是由于第一次启动创建的管理线程在第二次启动之前没有正确清除。
因此,在第二次启动时,myprogram 尝试使用 pthread 创建线程,并且尚未删除旧的线程管理,因此会导致崩溃。
有没有办法在我第一次启动结束时或在我第二次启动C开始时终止管理线程?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_t test_thread;
void *thread_test_run (void *v)
{
int i=1;
while(1)
{
printf("into thread %d\r\n",i);
i++;
sleep(1);
}
return NULL
}
int main()
{
// ps aux | grep myprogram ---> show 1 myprogram (1 for the main application)
pthread_create(&test_thread, NULL, &thread_test_run, NULL);
// ps aux | grep myprogram ---> show 3 myprogram
// (1st for the main application)
// (2nd for the management thread. thread which manage all created thread)
// (3rd for the created thread)
sleep (20);
pthread_cancel(test_thread);
// ps aux | grep myprogram ---> show 2 myprogram and
// (1st for the main application)
// (2nd for the management thread. thread which manage all created thread)
sleep(100);
// in this period (before the finish of myprogram)
// I execute killall to kill myprogram
// and then immediately I re-launch myprogram and then the program crash
// because the management thread is not immediately killed
}
顺便提一句:
linux使用libuClibc-0.9.30.1.so
并根据这个问题How to kill all subprocess created with pthread_create after canceling a thread? 此 libc 使用 linux 线程实现,pthread
并且不使用带有 NPTL(“Native posix thread library”)实现的 libc,因此仅针对这种 libc 情况创建管理线程。