Reputation: 166
I am trying to start a thread execution doing the following:
#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);
}
Executing this piece of code, the result is a core dumped. Surprisingly, when I change the function doTask to this one:
void doTask(callback_function a){
a();
}
It works, or even doing that also works:
int main(){
callback_function print = printer;
std::thread t1(printer);
}
Does somebody knows what I'm missing or doing wrong?
Upvotes: 0
Views: 67
Reputation: 5054
Both cases are wrong. The object std::thread t1
lives until the function doTask
exits. Then the thread object is trying to be destroying while callback_function
still works.
You should wait for thread to stop it's work and then to delete it.
int main(){
callback_function print = printer;
std::thread t1(printer);
// do some other stuff
t1.join();
}
Upvotes: 4
Reputation: 12757
The problem is that the main thread ends before that the t1
thread has finished its work. You should add t1.join()
or t1.detach()
before exiting doTask.
Upvotes: 1