gpt4 book ai didi

c++ - boost::fiber 调度 - 何时以及如何

转载 作者:行者123 更新时间:2023-11-30 04:59:55 26 4
gpt4 key购买 nike

根据文档

the currently-running fiber retains control until it invokes some operation that passes control to the manager

我只能考虑一个操作 - boost::this_fiber::yield这可能会导致从光纤到光纤的控制切换。但是,当我运行类似

bf::fiber([](){std::cout << "Bang!" << std::endl;}).detach();
bf::fiber([](){std::cout << "Bung!" << std::endl;}).detach();

我得到类似的输出

Bang!Bung!
\n
\n

这意味着控制在 << 之间传递运营商从一根光纤到另一根光纤。这怎么可能发生?为什么?在 boost::fiber 的上下文中从光纤到光纤的控制传递的一般定义是什么?图书馆?

编辑001:没有代码就无法逃脱:

#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

最佳答案

好吧,我错过了几件事,首先,我的结论是基于对 boost::fiber 中的东西是如何工作的误解。
问题中提到的构造函数中的行 bf::use_scheduling_algorithm<bf::algo::work_stealing>(2);
GreenExecutor 所在的线程中安装调度程序实例已创建(在主线程中),因此,在启动两个 worker 时 fiber s 我实际上启动了两个将要处理提交的线程 fiber s 反过来会处理这些 fibers异步混合 std::cout输出。没有魔法,一切都按预期工作,boost::fiber::yield仍然是将控制从一根光纤传递到另一根光纤的唯一选择

关于c++ - boost::fiber 调度 - 何时以及如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51017582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com