gilgamash
gilgamash

Reputation: 902

Boost thread finished callback available

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!

Upvotes: 1

Views: 1515

Answers (2)

kgbook
kgbook

Reputation: 378

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;
}

Upvotes: 2

hkaiser
hkaiser

Reputation: 11521

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;
}

Upvotes: 2

Related Questions