本文介绍了如何在线程创建和退出时调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <pthread.h>
#include <iostream>
using namespace std;
void OnCreateThread()
{
cout << "Create a thread." << endl;
}
void OnExitThread()
{
cout << "Exit a thread." << endl;
}
void f(void*) {}
int main()
{
//
// What to do here ???
//
pthread_t dummy;
pthread_create(&dummy, 0, f, 0);
pthread_create(&dummy, 0, f, 0);
while (true);
}
代码创建了两个本机线程,而不是std::thread
,我希望它输出如下:
The code creates two native threads, other than std::thread
, and I want it to output as follows:
Create a thread.
Create a thread.
Exit a thread.
Exit a thread.
可以在Windows下使用FlsXXX函数完成.
It can be done under Windows by using FlsXXX functions.
但是,我不知道它是否也可以在Linux下完成.
However, I don't know whether it can also be done under Linux.
Linux下是否有标准方法?
Is there a standard way under Linux?
推荐答案
至少存在一个pthread_cleanup_push
函数,该函数可让您添加一个在线程终止后立即被调用的函数.从未听说过可以创建相同的东西,但是某些API可能会有这样的东西.
There exists at least a pthread_cleanup_push
function that lets you add a function that will be called just after thread termination. Never heard about the same for creation, but some API may have such.
这篇关于如何在线程创建和退出时调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!