boost 1.53 的 boost.coroutine協程庫


評論區反饋,已失去實效性,請關注boost官方最新動態

--------------------------------------------

boost庫總是會給人帶來驚喜,換了1.53好久,一直沒去看更新內容,今天用到原子操作了,一看Boost里面有,good!

再看有一個boost.coroutine,哈,爽!查了下用法,看來入庫后比原版簡化了不少,應該算是對稱協程,boost特點,用起來特別簡單

#include <boost/coroutine/coroutine.hpp>
#include <string>
int main(int argc, char* argv[])
{
  // 類型聲明類似boost.function不過這里不是函數原型,而算是調用與返回的通訊協議
    typedef boost::coroutines::coroutine<std::string(std::string)>  myCoro_t;

  // 函數體的原型是被固定為void(T::caller_type&)類型的和作者原版不太一樣
    myCoro_t coro([](myCoro_t::caller_type& caller){        
            while(caller.has_result())
            {
                if (caller.get()=="exit")
                    return;
                std::cout << caller.get() << std::endl;
                caller("ok");
            }
        },"this your arg");  // 初始化可以不傳入參數,但是調用get前需要判斷has_result否則觸發斷言
  if (coro.has_result())
        std::cout << coro.get() << std::endl;
    
    coro("give you the arg again");
    if (coro.has_result())
        std::cout << coro.get() << std::endl;

    coro("exit");
    if (!coro)  // 執行完畢或者被設置空后為false
       std::cout << "the coroutine is complete" << std::endl;

    return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM