1

我想使用由工作线程托管的 Boost.Fibers 而不仅仅是线程。我想在编写下面显示的代码时,我已经按照手册中的所有内容完成了所有操作,但它似乎不起作用——输出中缺少“<anonymous> called”。

有谁知道为什么?

#include <boost/fiber/all.hpp>
#include <boost/thread/barrier.hpp>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <thread>

#define RIGHTNOW (std::cerr << "[thread " << std::this_thread::get_id() << "] ")

static inline
void run_worker(uint32_t threads, boost::barrier& barrier) {
    RIGHTNOW << "run_worker(" << threads << ", " << (void*)&barrier << ") called" << std::endl;

    boost::fibers::use_scheduling_algorithm<boost::fibers::algo::work_stealing>(threads);

    barrier.wait();
    RIGHTNOW << "run_worker(" << threads << ", " << (void*)&barrier << ") awaited everything else" << std::endl;

    boost::fibers::mutex mutex;
    boost::fibers::condition_variable_any cv;

    mutex.lock();
    RIGHTNOW << "run_worker(" << threads << ", " << (void*)&barrier << ") locked mutex" << std::endl;

    cv.wait(mutex);
    RIGHTNOW << "run_worker(" << threads << ", " << (void*)&barrier << ") awaited CV" << std::endl;

    mutex.unlock();
}

void start_engine(uint32_t threads) {
    RIGHTNOW << "start_engine(" << threads << ") called" << std::endl;

    if (threads < 1u) {
        threads = 1;
    }

    boost::barrier barrier (threads + 1u);
    auto scheduler ([threads, &barrier]() { run_worker(threads, barrier); });

    for (auto i (threads); i; --i) {
        std::thread(scheduler).detach();
    }

    barrier.wait();
    RIGHTNOW << "start_engine(" << threads << ") awaited everything else" << std::endl;
}

int main() {
    RIGHTNOW << "main() called" << std::endl;

    start_engine(1);

    boost::fibers::fiber([]() {
        RIGHTNOW << "<anonymous> called" << std::endl;
        _Exit(1);
    }).detach();

    RIGHTNOW << "main() waiting" << std::endl;
    for (;;) {
    }
}
clang++ -std=c++11 -I ~/homebrew/Cellar/boost/1.70.0/include -L ~/homebrew/Cellar/boost/1.70.0/lib -l boost_fiber-mt -l boost_context-mt -l boost_thread-mt -o fibers fibers.cpp
./fibers
4

0 回答 0