Skip to content

Instantly share code, notes, and snippets.

@novacrazy
Last active July 28, 2016 13:11
Show Gist options
  • Save novacrazy/9d17086e1bf1b0b38569eae0d6900e2d to your computer and use it in GitHub Desktop.
Save novacrazy/9d17086e1bf1b0b38569eae0d6900e2d to your computer and use it in GitHub Desktop.
Async callbacks
#include <iostream>
#include <chrono>
#include <thread>
#define UV_OVERLOAD_OSTREAM
#include "uv++.hpp"
using namespace std;
int main() {
//Just use the default loop
auto loop = uv::default_loop();
//Create an asynchronous task
auto a = loop->async<int, string>( [&]( auto, int i ) {
cout << "Sent: " << i << endl;
return "Hello, World!";
} );
/*
* An async trigger MUST be called from another thread if it blocks to receive a return value.
*
* Otherwise, it'll block the same thread the event looping is running on and deadlock everything.
* */
thread( [=]() {
//Trigger the asynchronous task and wait on the result
cout << "Returned: " << a->send( 42 ).get() << endl;
} ).detach();
//Start the event loop
loop->start();
return 0;
}
Sent: 42
Returned: Hello, World!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment