views:

1166

answers:

4

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.

A: 

Perhaps you want to emit a signal?

I really liked Qt's signals and slots functionality, and I know Boost has signals/slots as well. I've never used signals/slots in Boost, though.

KeyserSoze
The only problem with that is that this may not work asynchronously, and if it does then it probably needs an event loop set up to "post" the signal to the loop. Otherwise you're back to just throwing it on a thread and forgetting about it.
Jim Crafton
+2  A: 

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.

Greg Rogers
+2  A: 

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.

David Smith
+1  A: 

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.

Eclipse