Last active
July 28, 2016 13:11
-
-
Save novacrazy/9d17086e1bf1b0b38569eae0d6900e2d to your computer and use it in GitHub Desktop.
Async callbacks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sent: 42 | |
Returned: Hello, World! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment