IS there a way of running a function back on the main thread ?
So if I called a function via Async that downloaded a file and then parsed the data. It would then call a callback function which would run on my main UI thread and update the UI ?
I know threads are equal in the default C++ implementation so would I have to create a shared pointer to my main thread. How would I do this and pass the Async function not only the shared pointer to the main thread but also a pointer to the function I want to rrun on it and then run it on that main thread ?
Are you looking for
std::launch::deferred
? Passing this parameter to std::async makes the task executed on the calling thread when the get() function is called for the first time.I have been reading C++ Concurrency in Action and chapter four (AKA "The Chapter I Just Finished") describes a solution.
The Short Version
Have a shared
std::deque<std::packaged_task<void()>>
(or a similar sort of message/task queue). Yourstd::async
-launched functions can push tasks to the queue, and your GUI thread can process them during its loop.There Isn't Really a Long Version, but Here Is an Example
Shared Data
The
std::async
FunctionThe GUI Thread
Notes:
I am (always) learning, so there is a decent chance that my code is not great. The concept is at least sound though.
The destructor of the return value from
std::async
(astd::future<>
) will block until the operation launched withstd::async
completes (seestd::async
), so waiting on the result of a task (as I do in my example) inone_off
might not be a brilliant idea.You may want to (I would, at least) create your own threadsafe MessageQueue type to improve code readability/maintainability/blah blah blah.
I swear there was one more thing I wanted to point out, but it escapes me right now.
Full Example
Dat Output