Skip to content

Boost Fiber

Fiber

跑的比 go 慢兩倍

cpp
#include <boost/fiber/all.hpp>
#include <chrono>
#include <iostream>
#include <vector>
using Chan = boost::fibers::unbuffered_channel<int>;
void producer(Chan& chan, int count) {
    for (int i = 0; i < count; ++i) {
        chan.push(i);
        boost::this_fiber::yield();
    }
}
void consumer(Chan& chan, int count) {
    for (int i = 0; i < count; ++i) {
        int v;
        if (chan.pop(v) != boost::fibers::channel_op_status::success) {
            std::cerr << "channel pop error" << std::endl;
        }
        boost::this_fiber::yield();
    }
}
template <typename Func> double perfms(Func&& func) {
    auto t1 = std::chrono::high_resolution_clock::now();
    func();
    auto t2 = std::chrono::high_resolution_clock::now();
    return std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1)
               .count() *
           1000;
}
int main(int argc, char** argv) {
    Chan chan;
    int count = atoi(argv[1]);
// boost::fibers::use_scheduling_algorithm<boost::fibers::algo::round_robin>();
    std::vector<boost::fibers::fiber> fibers;
    double p1, p2, c1, c2;
    fibers.emplace_back(
        [&]() { p1 = perfms(std::bind(producer, std::ref(chan), count)); });
    fibers.emplace_back(
        [&]() { p2 = perfms(std::bind(producer, std::ref(chan), count)); });
    fibers.emplace_back(
        [&]() { c1 = perfms(std::bind(consumer, std::ref(chan), count)); });
    fibers.emplace_back(
        [&]() { c2 = perfms(std::bind(consumer, std::ref(chan), count)); });
    for (auto& fiber : fibers) {
        fiber.join();
    }
    std::cout << "producer: " << p1 << "ms " << p2 << "ms" << std::endl;
    std::cout << "consumer: " << c1 << "ms " << c2 << "ms" << std::endl;
    return 0;
}

Changelog

Just observe 👀