Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #define COROUTINE_VERSION 2
- #define USE_FIBERS 1 /* only for COROUTINE_VERSION == 2 */
- #if COROUTINE_VERSION == 1
- #include <boost/coroutine/all.hpp>
- using __Coro = boost::coroutines::coroutine<void>;
- __Coro::pull_type & get_empty_coroutine()
- {
- static __Coro::pull_type empty_coroutine;
- return empty_coroutine;
- }
- #endif
- #if COROUTINE_VERSION == 2
- #if USE_FIBERS == 1
- #define BOOST_USE_WINFIBERS
- #endif
- #include <boost/coroutine2/all.hpp>
- #include <boost/system/config.hpp>
- using __Coro = boost::coroutines2::coroutine<void>;
- __Coro::pull_type & get_empty_coroutine()
- {
- static __Coro::pull_type empty_coroutine
- (
- [](__Coro::push_type & /*yield*/)
- {
- return 42;
- }
- );
- __Coro::pull_type tmp(std::move(empty_coroutine));
- return empty_coroutine;
- }
- #endif
- #include <boost/lockfree/queue.hpp>
- boost::lockfree::queue<__Coro::pull_type *> coroutine_queue(1024);
- __Coro::pull_type * get_coroutine()
- {
- __Coro::pull_type * result = nullptr;
- bool got_result = coroutine_queue.pop(result);
- return got_result ? result : nullptr;
- }
- void Post2UI(__Coro::pull_type * coro)
- {
- bool result = coroutine_queue.push(coro);
- assert(result);
- }
- /*template<typename L> auto __await_async(__Coro::pull_type * coro, __Coro::push_type & yield, L lambda)->decltype(lambda())
- {
- auto f = async(launch::async, [=]() {
- auto r = lambda();
- Post2UI(coro);
- return r;
- });
- yield();
- return f.get();
- }*/
- void CallFromUI(void* c)
- {
- auto coro = static_cast<__Coro::pull_type *>(c);
- (*coro)();
- if (!*coro) delete coro;
- }
- #define async_code(block) { __Coro::pull_type * __coro=new __Coro::pull_type(std::move(get_empty_coroutine())); *__coro=__Coro::pull_type([=](__Coro::push_type & __yield){block});}
- //#define await_async(l) __await_async(__coro, __yield, l)
- template<typename L> auto __await_sync(__Coro::pull_type * coro, __Coro::push_type& yield, L lambda)->decltype(lambda())
- {
- Post2UI(coro);
- yield();
- return lambda();
- }
- #define await(l) __await_sync(__coro, __yield, l)
- //////////////////////////////////////////////////////////////////////////////
- int CalcSomething(int params) { return params; }
- void ProcessResult(int result) { std::cout << result; }
- void Handler2();
- void Handler(int params) async_code
- (
- for (int i = 0; i != 10; ++i)
- {
- if (i == 5 && params == 1)
- {
- Handler2();
- }
- auto r = await
- (
- [&]
- {
- return CalcSomething(params);
- }
- );
- ProcessResult(r);
- }
- std::cout << "leaving coroutine " << params << std::endl;
- )
- void Handler2()
- {
- Handler(2);
- }
- int main()
- {
- Handler(1);
- for (;;)
- {
- auto * c = get_coroutine();
- if (c)
- {
- std::cout << "G";
- CallFromUI(c);
- std::cout << "g";
- }
- else
- {
- break;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement