Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost: Fire and forget asynchronous function call?

I would like invoke a function call in a one shot manner. What's the best way to do this in Boost / C++?

I would like to pass it two parameters and do not need a result.

like image 647
JeffV Avatar asked Sep 30 '08 22:09

JeffV


3 Answers

Well you can spin up a thread and then never join it again. Something like:

boost::thread some_thread(&SomeFunction, param1, param2);

Once the some_thread variable goes out of scope, the thread of execution will be detached and will not be able to be joined again. It's a waste to spin up a thread unless the processing time of this function is significant though.

like image 92
Greg Rogers Avatar answered Nov 18 '22 19:11

Greg Rogers


I haven't used boost::thread in awhile but I see a quick example on the documentation page for the class:

void find_the_question(int the_answer);

boost::thread deep_thought_2(find_the_question,42);

I believe as soon as it finishes the function, the thread will exit. This may not be what you want in that once the thread goes out of scope, it will be destroyed. If that's not going to work, you probably need to create a long running thread pool and then pass your functors as boost::bind compositions.

like image 3
David Smith Avatar answered Nov 18 '22 21:11

David Smith


Depending on how often you are doing this, you might be best off creating a pool of threads, along with a work queue. Creating a thread can create a lot of overhead if you are trying to do it dozens of times a second. If you don't care about the return value, that makes it really easy.

Spin up a thread or two (or ten); have a thread-safe queue of functors to call (bind the parameters to the function and put that on the queue); the threads wait on the queue for something to show up, the first thread to wake up gets to process the work. When a thread is done running a job, it waits on the queue again.

Take a look at this project for an idea of one way to do it.

Of course if you are only making asynchonous calls every couple of seconds to improve a UI's responsiveness, it'd be easier to just start up a new thread every time.

like image 1
Eclipse Avatar answered Nov 18 '22 20:11

Eclipse