协程示例

协程(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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值