根据文档
当前运行的光纤保留控制权,直到它调用某些 将控制权传递给经理的操作
我只能考虑一种操作-boost::this_fiber::yield
,这可能会导致控制从光纤切换到光纤。但是,当我运行类似
bf::fiber([](){std::cout << "Bang!" << std::endl;}).detach();
bf::fiber([](){std::cout << "Bung!" << std::endl;}).detach();
我得到类似
的输出B!ung!
\ n
\ n
这意味着控制已在<<
个运算符之间从一根光纤传递到另一根光纤。它怎么可能发生?为什么?在boost::fiber
库的上下文中,控制从光纤传递到光纤的一般定义是什么?
EDIT001: 没有代码就无法逃脱:
#include <boost/fiber/fiber.hpp>
#include <boost/fiber/mutex.hpp>
#include <boost/fiber/barrier.hpp>
#include <boost/fiber/algo/algorithm.hpp>
#include <boost/fiber/algo/work_stealing.hpp>
namespace bf = boost::fibers;
class GreenExecutor
{
std::thread worker;
bf::condition_variable_any cv;
bf::mutex mtx;
bf::barrier barrier;
public:
GreenExecutor() : barrier {2}
{
bf::use_scheduling_algorithm<bf::algo::work_stealing>(2);
worker = std::thread([this] {
bf::use_scheduling_algorithm<bf::algo::work_stealing>(2);
// wait till all threads joining the work stealing have been registered
barrier.wait();
mtx.lock();
// suspend main-fiber from the worker thread
cv.wait(mtx);
mtx.unlock();
});
// wait till all threads have been registered the scheduling algorithm
barrier.wait();
}
template<typename T>
void PostWork(T&& functor)
{
bf::fiber {std::move(functor)}.detach();
}
~GreenExecutor()
{
cv.notify_all();
worker.join();
}
};
int main()
{
GreenExecutor executor;
std::this_thread::sleep_for(std::chrono::seconds(1));
int i = 0;
for (auto j = 0ul; j < 10; ++j) {
executor.PostWork([idx {++i}]() {
auto res = pow(sqrt(sin(cos(tan(idx)))), M_1_PI);
std::cout << idx << " - " << res << std::endl;
});
}
while (true) {
boost::this_fiber::yield();
}
return 0;
}
输出
2-1--nan
0.503334 3-4-0.861055
0.971884 5-6-0.968536
-nan 7-8-0.921959
0.9580699
-10-0.948075
0.961811
答案 0 :(得分:0)
好吧,我错过了几件事,首先,我的结论基于对boost::fiber
中的东西如何工作的误解。
问题中提到的构造函数中的行
bf::use_scheduling_algorithm<bf::algo::work_stealing>(2);
正在在创建GreenExecutor
实例的线程中安装调度程序(在主线程中),因此,当启动两个工作线程fiber
时,我实际上是在初始化两个线程,这些线程将处理提交的{{1 }}依次将异步处理这些fiber
从而混合fibers
输出。没什么魔术,一切都按预期工作,std::cout
仍然是将控制权从一根光纤传递到另一根光纤的唯一选择