0

I want to run a callback function in a pthread.

I am currently stuck at the following code:

//maintest.cpp
....
main{
...
//setting up the callback function SimT:
boost::asio::io_service io;
boost::asio::deadline_timer t(io);
SimT d(t);

//calling io.run() in another thread with io.run()
pthread_t a;
pthread_create( &a, NULL, io.run(),NULL); ----->Here I dont know how to pass the io.run() function
...
//other stuff that will be executed during io.run()
}

How should I specify io.run() in the pthread_create argument? Thank you

user2212461
  • 3,105
  • 8
  • 49
  • 87

2 Answers2

2

You'll need to pass a pointer to a non-member function, for example:

extern "C" void* run(void* io) {
    static_cast<io_service*>(io)->run();
    return nullptr; // TODO report errors
}

pthread_create(&a, nullptr, run, &io);

Of course, these days there's no need to muck around with native threading libraries:

std::thread thread([&]{io.run();});
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

You'd probably want to create a functor object and pass that in. For more information, check: C++ Functors - and their uses

Edit: If you're using C++11, this solution will be much cleaner: passing Lambda to pthread_create?

Community
  • 1
  • 1
yan
  • 20,644
  • 3
  • 38
  • 48
  • @user2212461: Not directly, since that's a C library which doesn't know about C++ classes and member functions. You'll need to write a C-compatible function to wrap up the member function call. – Mike Seymour Nov 06 '13 at 15:06