【发布时间】:2012-11-09 09:37:01
【问题描述】:
我有以下代码。构建应用程序是 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 cancelling a thread? 这个libc 使用pthread 的linux 线程实现并且不使用带有NPTL(“Native posix thread library”)实现的libc
所以只会为这种libc创建管理线程。
【问题讨论】: