I need a hint how to implement asynchronous function calls in C/C++ ( or names of frameworks/API calls for windows and/or linux )
The use case is following: A parent thread calls a function. The function creates a child thread and returning, so call is non-blocking and parent thread can continue to do some job.
For example pthread_join to get result is not suitable, so result must be stored somewhare in heap and parent must be notified about. What I want is something like callback function in parent thread, that would be executed after child thread is ready with job.
This is surprising, but I can not find a single example in google.
Thanks for help
Rather than using different frameworks, and noting that you've mentioned
pthread_join()
in your question, you can still achieve the desired effect with POSIX C. For that, you can use signals to acknowledge a thread of a parallel task completion. In this method, you install a signal handler for a user-defined signal (SIGUSR1
, for example), create a set of working threads with different tasks and let them signalize the parent when they are complete.The following program illustrates the attempt. In the example, I use
SIGUSR1
to inform the parent thread of the completion of some processing. The parent thread is kept busy doing some I/O until interrupted by the child thread. Note that, for clarity, no error-handling code of any sort has been put.The example uses the LinuxThreads implementation of signals, which is quite different from what POSIX defines. If you are concerned with portability or compliance, the above solution should be further revised.
C++0x provides
std::async
for this. Here's an existing implementation, a discussion, and Wikipedia.I suggest you check out http://www.threadingbuildingblocks.org/.
The Task class (http://cache-www.intel.com/cd/00/00/30/11/301114_301114.pdf#page=95) may be a starting point.
I see in your reply to Starkey that the main thread is a UI thread.
I've used several different GUI toolkits and all of them allow you to post a message from a different thread. So have the worker thread post a GUI message when it is complete, the handler will then run in the main thread.
In Windows, use
PostMessage
.In Linux, use
XtAppAddSignal
andXtNoticeSignal
Boost.Thread
I believe this does the job well. Spin up the function call as a new thread and just don't bother joining it. It'll take care of that when it finishes anyway I believe.
You could set it up so the child sends a signal to the parent when it finishes using Boost.Signals. This signal would be linked to the parent's callback function.
You'll have to set up some kind of infrastructure to notify the caller that the work is done. This could be done with an Observer pattern type. A message type infrastructure can be used as well.
The real question is what is your parent going to do while it waits. Do you want it to poll for results? Or get notified?