Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is in c++11 something similar for threads to node.js/javascript callbacks?

Tags:

c++

c++11

If I start a thread from the main thread, is there any option to hook callback which the new thread is going to trigger. Callback should be executed in the main thread.

At the moment I am using future for this task but I want to avoid waiting for result (result is boolean, in case true everything is ok, in case false I need to start again thread to try to do task). Is in c++11 something similar to node.js/javascript callbacks?

like image 257
Damir Avatar asked Jun 27 '26 06:06

Damir


2 Answers

There is nothing explicitly for doing this in current standard C++.

std::future::then() is in the standardization pipeline and may be included in C++1y or a TR.

There are several third-party libraries which support this idiom:

  • Boost.Thread
  • Intel Threading Building Blocks (TBB)
  • OpenMP
  • Microsoft Parallel Patterns Library (PPL) [Windows only]
  • Microsoft Casablanca

Related: Asio is a C++ asynchronous I/O library that supports this idiom just for non-blocking I/O operations, not general computation operations. (Node.js is mainly used for I/O, so this might be adequate.)

Otherwise, you can roll your own workaround:

auto myFuture = std::async([](){
    doWork();
}).share();
auto myNextFuture = std::async([=](){
    myFuture.wait();
    doMoreWork();
});

You can package this up into a reusable helper:

template <typename Future, typename Work>
auto after(Future f, Work w) -> std::future<decltype(w())>
{
    return std::async([=]() -> decltype(w()) { f.wait(); return w(); });
}

And use it like so:

auto myFuture = std::async([](){
    doWork();
});
auto myNextFuture = after(myFuture.share(), [](){
    doMoreWork();
});

With this approach you pay for the cost of an extra thread (probably).

Related: C++ Concurrency talk by Herb Sutter.

like image 173
Oktalist Avatar answered Jun 29 '26 19:06

Oktalist


std::future::then() and the continuation implementations listet by Oktalist will do a good job, if you do not really need to execute the callback in the main thread. But if it is a requirement they will not be enough.

If you have an event loop running ( most GUI applications will have one ) you could notify the loop from the continuation to execute your callback.

In Qt you could send a signal from inside the continuation to an object living in the main thread. The event loop will eventually execute the slot in the main thread.

If you do not have an event loop boost coroutines may be an option, but I have not used them myself.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!