tonytr
tonytr

Reputation: 166

Can not start threads from pointer to function, C++

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

Answers (2)

borisbn
borisbn

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

Paolo M
Paolo M

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

Related Questions