1

I am looking for a way to call a callback function when a boost thread (boost version 1.60, ordinary thread, no thread group or pool) finishes. I have read this

How can I tell reliably if a boost thread has exited its run method?

but I need some kind of callback. Any idea how to do this? Do I have to create some kind of a conditional variable?

Thanks for help!

Community
  • 1
  • 1
gilgamash
  • 862
  • 10
  • 31
  • 1
    There is no callback defined on `boost::thread` finishing. Instead, you could join the thread and than call whatever callback you want yourself. – SergeyA Feb 24 '16 at 14:32
  • Thanks for the reply. I guessed so. I think I will finally go with that or either create a conditional variable. Thanks! – gilgamash Feb 24 '16 at 14:35
  • I don't understand the problem? If you want to know when a thread is finishing by callback, have it call your callback thing as its last line before exiting. – Martin James Feb 24 '16 at 14:57
  • Two other threads are waiting for an intermediate result, that is the situation. I decided for the condVar solution. Easy to implement and works fine. – gilgamash Feb 25 '16 at 08:45

2 Answers2

2

The simplest solution would be to wrap your original thread function:

#include <boost/thread.hpp>
#include <iostream>

void callback()
{
    std::cout << "callback invoked" << std::endl;
}

void orig_thread_func()
{
    std::cout << "thread function invoked" << std::endl;
}

void wrapper(void (*func)())
{
    func();        // invoke your original thread function
    callback();    // invoke callback
}

int main()
{
    boost::thread t(&wrapper, &orig_thread_func);
    t.join();
    return 0;
}
hkaiser
  • 11,403
  • 1
  • 30
  • 35
2

Maybe you need a interface like atexit which register callback on process exit.

So Using at_thread_exit, see this_thread.atthreadexit

Usage:

void thread_exit_callback(){
  std::cout <<"thread exit now!" <<std::endl;
}

void thread_func(){  
  boost::this_thread::at_thread_exit(thread_exit_callback);
}

int main() {
  boost::thread t(thread_func);
  ...
  return 0;
}
kgbook
  • 388
  • 4
  • 16
  • Seriously? Answering this question nearly three years after it was posted? Meanwhile I won't even use Boost any longer for threads, considering c++ 17 features... – gilgamash Dec 11 '18 at 08:09
  • 3
    You didn't update your question that you no longer use `boost::thread`. Perhaps someone else has the same question. – kgbook Dec 11 '18 at 09:41