Boost::context模块的Fiber堆栈测试程序
Boost是一个C++库集合,其中有一个很有用的模块叫做boost::context,它提供了一种轻量级协程实现——Fiber,它在调度上比线程更轻量级,而且可以自己控制堆栈大小。在使用boost::context模块的时候,需要使用一些相关的类和函数,这里提供一份简单的示例代码来演示如何使用。
#include <iostream>
#include <boost/context/fiber.hpp>
using namespace std;
using namespace boost::context;
fiber main_fiber; //定义主协程对象
fiber* f1; //定义子协程指针
char stack_buf1[1024*1024]; //定义子协程1的堆栈空间
void f1_func(int num) {
cout << "Coroutine 1 starts. Parameter: " << num << endl;
*f1 = boost::context::fiber(main_fiber); //切回主协程
cout << "Coroutine 1 ends." << endl;
}
int main() {
f1 = new fiber(f1_func, 123, stack_buf1);