我正在尝试启动线程执行,执行以下操作:
#include <thread>
#include <stdio.h>
typedef void (*callback_function)(void);
void printer(){
printf("Something\n");
}
void doTask(callback_function a){
std::thread t1(a);
}
int main(){
callback_function print = printer;
doTask(print);
}
执行这段代码,结果是core dumped。令人惊讶的是,当我将函数 doTask 更改为这个函数时:
void doTask(callback_function a){
a();
}
它有效,甚至这样做也有效:
int main(){
callback_function print = printer;
std::thread t1(printer);
}
有人知道我遗漏了什么或做错了什么吗?
最佳答案
这两种情况都是错误的。对象 std::thread t1
存在 直到函数 doTask
退出。然后线程对象试图销毁,而 callback_function
仍然有效。
你应该等待线程停止它的工作然后删除它。
int main(){
callback_function print = printer;
std::thread t1(printer);
// do some other stuff
t1.join();
}
关于c++ - 无法从指向函数的指针启动线程,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31721882/