根据文件
当前运行的光纤保留控制,直到它调用一些将控制传递给管理器的操作为止。
我只能想到一种操作-- boost::this_fiber::yield,它可能导致从光纤到光纤的控制开关。但是,当我运行这样的
bf::fiber([](){std::cout << "Bang!" << std::endl;}).detach();
bf::fiber([](){std::cout << "Bung!" << std::endl;}).detach();我得到的输出就像
砰!砰!\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}
{
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();
});
bf::use_scheduling_algorithm<bf::algo::work_stealing>(2);
// 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
发布于 2018-06-27 17:19:19
好吧,有几件事我错过了,首先,我的结论是基于对boost::fiber中的东西是如何工作的误解
问题bf::use_scheduling_algorithm<bf::algo::work_stealing>(2);中提到的构造函数中的行
在创建GreenExecutor实例的线程中安装调度程序(在主线程中),因此,在启动两个工作线程fiber的时候,我实际上启动了两个线程,它们将处理提交的fiber,然后异步处理这些fibers,从而混合std::cout输出。没有魔力,一切都像预期的那样工作,boost::fiber::yield仍然是将控制从一种光纤传递到另一种光纤的唯一选择。
https://stackoverflow.com/questions/51017582
复制相似问题