2 // Copyright Oliver Kowalke 2015.
3 // Distributed under the Boost Software License, Version 1.0.
4 // (See accompanying file LICENSE_1_0.txt or copy at
5 // http://www.boost.org/LICENSE_1_0.txt)
7 // based on https://github.com/atemerev/skynet from Alexander Temerev
12 #include <condition_variable>
25 #include <boost/fiber/all.hpp>
27 #include "barrier.hpp"
28 #include "bind/bind_processor.hpp"
30 using clock_type = std::chrono::steady_clock;
31 using duration_type = clock_type::duration;
32 using time_point_type = clock_type::time_point;
33 using channel_type = boost::fibers::buffered_channel< std::uint64_t >;
34 using allocator_type = boost::fibers::fixedsize_stack;
35 using lock_type = std::unique_lock< std::mutex >;
37 static bool done = false;
38 static std::mutex mtx{};
39 static boost::fibers::condition_variable_any cnd{};
42 std::uint64_t skynet(allocator_type& salloc, std::uint64_t num, std::uint64_t size, std::uint64_t div)
47 std::vector<boost::fibers::future<std::uint64_t> > results;
48 results.reserve( div);
50 for ( std::uint64_t i = 0; i != div; ++i) {
51 std::uint64_t sub_num = num + i * size;
52 results.emplace_back(boost::fibers::async(
53 boost::fibers::launch::dispatch
54 , std::allocator_arg, salloc
56 , std::ref( salloc), sub_num, size, div));
59 std::uint64_t sum = 0;
60 for ( auto& f : results)
69 void thread( unsigned int max_idx, unsigned int idx, barrier * b) {
70 bind_to_processor( idx);
71 boost::fibers::use_scheduling_algorithm< boost::fibers::algo::work_stealing >( max_idx, idx);
74 cnd.wait(lk, [](){ return done; });
80 unsigned int cpus = std::thread::hardware_concurrency();
82 unsigned int max_idx = cpus - 1;
83 boost::fibers::use_scheduling_algorithm< boost::fibers::algo::work_stealing >( max_idx, max_idx);
84 bind_to_processor( max_idx);
85 std::size_t size{ 1000000 };
86 std::size_t div{ 10 };
87 std::vector< std::thread > threads;
88 for ( unsigned int idx = 0; idx < max_idx; ++idx) {
89 threads.push_back( std::thread( thread, max_idx, idx, & b) );
91 allocator_type salloc{ allocator_type::traits_type::page_size() };
92 std::uint64_t result{ 0 };
93 duration_type duration{ duration_type::zero() };
95 time_point_type start{ clock_type::now() };
96 result = skynet( salloc, 0, size, div);
97 duration = clock_type::now() - start;
98 std::cout << "Result: " << result << " in " << duration.count() / 1000000 << " ms" << std::endl;
103 for ( std::thread & t : threads) {
106 std::cout << "done." << std::endl;
108 } catch ( std::exception const& e) {
109 std::cerr << "exception: " << e.what() << std::endl;
111 std::cerr << "unhandled exception" << std::endl;