2017-08-08 42 views
0

我怎樣才能做到這一點的情況純粹是異步:
讓我們假設有一個線程異步方式運行它創建時的一些條件fullfiled新的線程:C++回調的線頭和結果返回

class listener { 
    ... 
    void on_message(data_type data) { 
     if(some_specific_data_found(data)) { 
      do_some_work_in_new_thread(new_thread, data, callback_on_end); 
     } 
    } 
    ... 
    void callback_on_end(result_type result) { 
     do_some_work_in_this_thread(result); 
    } 
    ... 
} 

新創建的線程看起來是這樣的:

void new_thread(data_type data) { 
    auto result = do_some_work_here(); 
    push_result(result); // This result should be accessible in 
         // callback_on_end function. 
} 

我知道,我可以利用期貨實現類似的解決辦法,但我不希望調用任何阻塞函數像get()wait()

+2

你要像[未來::然後](http://en.cppreference.com/w/cpp/experimental/future/then)? – Jarod42

+2

[std :: future :: wait_for](http://en.cppreference.com/w/cpp/thread/future/wait_for)不會阻止。你的需求是不可用的嗎? – Galik

+0

將結果存儲在可輪詢的線程安全結構中。 –

回答

0

我以前boost::future::then這樣的:

 

    boost::future f = 
     boost::async(boost::launch::async, // start task in new thread 
        boost::bind(task_code, task_args)); 

    boost::future end_callback = f.then([&](auto i) { 
     auto result = i.get(); // i is of type future; get() returns object 
           // of type result_type_of_task_code 
           // get() is nonblocking 
     do_something(result); 
    });