我正在为 Linux(带有 PThreads)和 Windows(带有内置 WinThreads)创建一个 C++ 库,它可以附加到任何程序,并且需要在线程退出时调用一个函数,类似于 atexit 的工作原理过程。
我知道 pthreads 的 pthread_cleanup_push 和 pthread_cleanup_pop ,但它们对我不起作用,因为它们是添加另一个词法范围的宏,而我想在第一次调用我的库时声明这个函数,然后允许程序本身运行它自己的代码,但它需要。我在 Windows 中没有发现任何类似的东西。
请注意,这并不意味着我希望在线程停止时提醒外部线程,甚至我可以更改线程退出的方式,因为这是由程序本身控制的,我的库只是附加的乘车。
所以问题是:在这种情况下,当我无法控制线程的创建或销毁方式时,在 Windows 或 Linux 中,当线程关闭时调用我编写的函数,最好的方法是什么? ?
例如在主程序中:
void* threadFunc(void* arg)
{
printf("Hello world!\n");
return NULL;
}
int main(int argc, char** argv)
{
int numThreads = 1;
pid_t* pids = NULL;
pids = (pid_t*) calloc(sizeof(pid_t), numThreads);
pthread_create(&ntid, NULL, threadFunc, &nVal);
pthreads[0] = ntid;
pthread_join(pthreads[0], NULL);
return 0;
}
在图书馆:
void callMeOnExit()
{
printf("Exiting Thread!\n");
}
我希望在线程达到 return NULL 时调用 callMeOnExit;在这种情况下,以及当主线程到达时返回 0;。包装 pthread_exit 将适用于其他情况,并且可能是一种解决方案,但如果可能的话,我想要一个更好的解决方案。
如果有人对我如何能够做到这一点有任何想法,那就太好了!