金庆的专栏

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  423 随笔 :: 0 文章 :: 454 评论 :: 0 Trackbacks

协程(Coroutine)与线程类似,可看成用户线程,由用户调度,而不是系统调度。

示例创建1W个协程对象(TestCoro),然后随机调度运行。

1W个协程运行于同一个线程中。

协程构造绑定到CoroFun(), 与boost::thread的创建相同。


#include <iostream>
#include 
<vector>

#include 
<boost/bind.hpp>
#include 
<boost/coroutine/all.hpp>
#include 
<boost/make_shared.hpp>
#include 
<boost/shared_ptr.hpp>

using namespace std;

// test coroutine class
class TestCoro
{
public:
    
explicit TestCoro(int i);
    
~TestCoro();
    
public:
    
void operator()();
    
bool IsCompleted() const { return !m_coro; }
    
private:
    typedef boost::coroutines::coroutione
<void ()> Coro;
    
private:
    
void CoroFun(Coro::caller_type & ca);
    
private:
    
int m_i;
    Coro m_coro;
    Coro::caller_type 
* m_pCa;        
};

TestCoro::TestCoro(
int i)
: m_i(i)
, m_pCa(NULL)
{
    cout 
<< "TestCoro(" << i << ")" << endl;
    m_coro 
= Coro(boost::bind(&TestCoro::CoroFun, this, _1));
}

TestCoro::
~TestCoro()
{
    cout 
<< "~TestCoro(" << m_i << ")" << endl;
}

void TestCoro::operator()()
{
    m_coro();
}

void TestCoro::CoroFun(Coro::caller_type & ca)
{
    m_pCa 
= &ca;
    
    
for (int i = 0; i < 10; i++)
    {
        BOOST_ASSERT(m_pCa 
== &ca);
        (
*m_pCa)();
        cout 
<< m_i << " - " << i << endl;
    }
}

int main()
{
    typedef boost::shared_ptr
<TestCoro> TestCoroPtr;
    typedef std::vector
<TestCoroPtr> TestCoroVec;
    TestCoroVec v;
    
for (int i = 0; i < 10000; i++)
        v.push_back(boost::make_shared
<TestCoro>(i));
        
    cout 
<< "Start coroutines." << endl;
    
    
while (!v.empty)
    {
        size_t idx 
= rand() % v.size();
        TestCoroPtr 
& pCoro = v[idx];
        (
*pCoro)();
        
if (pCoro->IsCompleted())
        {
            v[idx] 
= v[v.size() - 1];
            v.pop_back();
        }
    }
    
    cout 
<< "Coroutines ended." << endl;
    
return 0;
}
posted on 2013-11-22 12:10 金庆 阅读(819) 评论(0)  编辑 收藏 引用 所属分类: 1. C/C++

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理