我在使用pthread的嵌入式系统上遇到线程管理问题。
我将代码缩减为此示例程序:
struct test;
struct destructionHelper
{
~destructionHelper()
{
printf("~destructionHelper()\n");
if(instance)
{
delete instance;
}
}
test* instance;
};
void* foo(void *)
{
printf("thread sleep for 15seconds\n");
sleep(15);
pthread_exit(NULL);
}
struct test{
static destructionHelper desHelper;
test()
{
pthread_create(&thread,NULL,foo,NULL);
desHelper.instance=this;
}
~test()
{
printf("joining...\n");
pthread_join(thread,NULL);
printf("joined\n");
}
pthread_t thread;
};
destructionHelper test::desHelper;
我将此测试类称为:
int main() {
new test();
printf("Sleep for 10 seconds\n");
sleep(10);
printf("main ended\n");
return 0;
}
我使用此destructionHelper
的原因是因为test
应该是一个单身人士(因为我没有C ++,对我来说没有Meyers单身人士)。
代码在我的桌面上工作正常但不是我想要的嵌入式平台。 (目标的内核是linux 2.6.28.9)
它会在到达pthread_join
时永远等待。在我调用ps
之前,系统似乎已关闭该线程(不再列出pthread_join
)。 pthread_join
的手册页说如果线程退出,它应该返回,但我想线程不再有效了?
有没有办法避免这种情况,同时还能释放我的单身人士?