1

根据文档

当前运行的纤程保留控制权,直到它调用一些将控制权传递给管理器的操作

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

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

我得到像

砰!砰!
\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}
    {   
        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

4

1 回答 1

1

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

于 2018-06-27T17:19:19.273 回答