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
13 #include <condition_variable>
24 #include <boost/fiber/all.hpp>
25 #include <boost/predef.h>
27 #include "barrier.hpp"
29 using allocator_type
= boost::fibers::fixedsize_stack
;
30 using channel_type
= boost::fibers::buffered_channel
< std::uint64_t >;
31 using clock_type
= std::chrono::steady_clock
;
32 using duration_type
= clock_type::duration
;
33 using lock_type
= std::unique_lock
< std::mutex
>;
34 using time_point_type
= clock_type::time_point
;
36 static bool done
= false;
37 static std::mutex mtx
{};
38 static boost::fibers::condition_variable_any cnd
{};
41 void skynet( allocator_type
& salloc
, channel_type
& c
, std::size_t num
, std::size_t size
, std::size_t div
) {
45 channel_type rc
{ 16 };
46 std::vector
< boost::fibers::fiber
> fibers
;
47 for ( std::size_t i
= 0; i
< div
; ++i
) {
48 auto sub_num
= num
+ i
* size
/ div
;
49 fibers
.emplace_back( boost::fibers::launch::dispatch
,
50 std::allocator_arg
, salloc
,
52 std::ref( salloc
), std::ref( rc
), sub_num
, size
/ div
, div
);
54 for ( auto & f
: fibers
) {
57 std::uint64_t sum
{ 0 };
58 for ( std::size_t i
= 0; i
< div
; ++i
) {
59 sum
+= rc
.value_pop();
65 void thread( unsigned int idx
, barrier
* b
) {
66 boost::fibers::numa::pin_thread( idx
);
67 boost::fibers::use_scheduling_algorithm
< boost::fibers::algo::shared_work
>();
70 cnd
.wait( lk
, [](){ return done
; });
76 boost::fibers::use_scheduling_algorithm
< boost::fibers::algo::shared_work
>();
77 unsigned int n
= std::thread::hardware_concurrency();
79 boost::fibers::numa::pin_thread( n
- 1);
80 std::size_t size
{ 1000000 };
81 std::size_t div
{ 10 };
82 std::vector
< std::thread
> threads
;
83 for ( unsigned int i
= 1; i
< n
; ++i
) {
84 threads
.emplace_back( thread
, i
- 1, & b
);
86 // Windows 10 and FreeBSD require a fiber stack of 8kb
87 // otherwise the stack gets exhausted
88 // stack requirements must be checked for other OS too
89 #if BOOST_OS_WINDOWS || BOOST_OS_BSD
90 allocator_type salloc
{ 2*allocator_type::traits_type::page_size() };
92 allocator_type salloc
{ allocator_type::traits_type::page_size() };
94 std::uint64_t result
{ 0 };
97 time_point_type start
{ clock_type::now() };
98 skynet( salloc
, rc
, 0, size
, div
);
99 result
= rc
.value_pop();
100 if ( 499999500000 != result
) {
101 throw std::runtime_error("invalid result");
103 auto duration
= clock_type::now() - start
;
108 for ( std::thread
& t
: threads
) {
111 std::cout
<< "duration: " << duration
.count() / 1000000 << " ms" << std::endl
;
113 } catch ( std::exception
const& e
) {
114 std::cerr
<< "exception: " << e
.what() << std::endl
;
116 std::cerr
<< "unhandled exception" << std::endl
;