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