-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfiber.hpp
1515 lines (1378 loc) · 48.7 KB
/
fiber.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-----------------------------------------------------------------------------------------
// fiber (header only)
// Copyright (C) 2022-24 Fix8 Market Technologies Pty Ltd
// by David L. Dight
// see https://github.com/fix8mt/fiber
//
// Lightweight header-only stackful per-thread fiber
// with built-in roundrobin scheduler x86_64 / linux only
//
// Distributed under the Boost Software License, Version 1.0 August 17th, 2003
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//----------------------------------------------------------------------------------------
#ifndef FIX8_FIBER_HPP_
#define FIX8_FIBER_HPP_
//----------------------------------------------------------------------------------------
#if !defined(__linux__) || !defined(__x86_64__)
#error "this fiber implementation only runs on x86_64/Linux"
#endif
//----------------------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include <type_traits>
#include <future>
#include <deque>
#include <array>
#include <chrono>
#include <algorithm>
#include <cstring>
#include <string>
#include <string_view>
#include <functional>
#include <stdexcept>
#include <ranges>
#include <bitset>
#include <mutex>
#include <utility>
#include <thread>
#include <concepts>
#include <condition_variable>
#include <set>
#include <unordered_set>
#include <atomic>
#include <fcntl.h>
#include <sys/resource.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <pthread.h>
//-----------------------------------------------------------------------------------------
// default fiber stack size; define in your app to override or set in ctor
#if !defined FIX8_FIBER_DEFSTKSZ
# define FIX8_FIBER_DEFSTKSZ 131072 // 128kb recommended
#endif
// default fiber name length
#if !defined FIX8_FIBER_FIBERNAMELEN
# define FIX8_FIBER_FIBERNAMELEN 16 // including null terminator
#endif
// define FIBER_NO_INSTRUMENTATION to disable instrumentation and printing
// if not defined, all instrumentation and printing is enabled (default)
#if !defined FIBER_NO_INSTRUMENTATION
# define FIX8_FIBER_INSTRUMENTATION_
#endif
// define FIBER_NO_MULTITHREADING to disable multi-threading support
// if not defined, multi-threading support is enabled (default)
#if !defined FIBER_NO_MULTITHREADING
# define FIX8_FIBER_MULTITHREADING_
#endif
//-----------------------------------------------------------------------------------------
namespace FIX8 {
//-----------------------------------------------------------------------------------------
#if defined FIX8_FIBER_MULTITHREADING_ && !defined f8_spin_lock && !defined f8_scoped_lock_impl
class f8_spin_lock final
{
std::atomic_flag _sl;
public:
void lock() noexcept { _sl.wait(true); } // std::memory_order_seq_cst
void unlock() noexcept { _sl.clear(); } // std::memory_order_seq_cst
};
template<typename T>
class f8_scoped_lock_impl
{
T& _local_mutex;
public:
f8_scoped_lock_impl(T& mutex) noexcept : _local_mutex(mutex) { _local_mutex.lock(); }
~f8_scoped_lock_impl() noexcept { release(); }
void release() noexcept { _local_mutex.unlock(); }
f8_scoped_lock_impl() = delete;
f8_scoped_lock_impl(const f8_scoped_lock_impl&) = delete;
f8_scoped_lock_impl& operator=(const f8_scoped_lock_impl&) = delete;
};
using f8_scoped_spin_lock = f8_scoped_lock_impl<f8_spin_lock>;
#endif
//-----------------------------------------------------------------------------------------
/// unique fiber id
class fiber_id
{
const void *_ptr{};
public:
fiber_id() noexcept = default;
constexpr explicit fiber_id(const void *ptr) noexcept : _ptr{ ptr } {}
#if defined FIX8_FIBER_INSTRUMENTATION_
template<typename charT, class traitsT> // TODO replace with std::format
friend std::basic_ostream<charT, traitsT>& operator<<(std::basic_ostream<charT, traitsT>& os, const fiber_id& what)
{
return what._ptr ? (os << std::dec << reinterpret_cast<uint64_t>(what._ptr) % 10000) : (os << "NaF");
}
std::string to_string() const noexcept
{
std::ostringstream ostr;
ostr << *this;
return ostr.str();
}
#endif
constexpr auto operator<=>(const fiber_id& other) const noexcept { return _ptr <=> other._ptr; }
constexpr bool operator!() const noexcept { return _ptr == nullptr; }
constexpr explicit operator bool() const noexcept { return _ptr; }
friend struct std::hash<fiber_id>;
};
//-----------------------------------------------------------------------------------------
enum class global_fiber_flags { retain, fairshare, hidedetached, skipmain, termthrow, excepthandling, count };
//-----------------------------------------------------------------------------------------
// used by FIX8::this_fiber
struct f8_this_fiber
{
inline static fiber_id get_id() noexcept;
#if defined FIX8_FIBER_INSTRUMENTATION_
inline static fiber_id get_prev_id() noexcept;
#endif
inline static fiber_id get_pid() noexcept;
inline static std::string_view name(std::string_view what) noexcept;
inline static std::string_view name() noexcept;
#if defined FIX8_FIBER_MULTITHREADING_
inline static void move(std::thread::id id);
#endif
inline static void yield() noexcept;
inline static void resume_main() noexcept;
inline static bool is_main() noexcept;
inline static bool schedule_main() noexcept;
template<typename Clock, typename Duration>
static void sleep_until(const std::chrono::time_point<Clock, Duration>& sltime);
template<typename Rep, typename Period>
static void sleep_for(const std::chrono::duration<Rep, Period>& retime);
};
using fiber_base_ptr = std::shared_ptr<class fiber_base>;
using fiber_queue = std::deque<fiber_base_ptr>;
using fiber_set = std::unordered_set<fiber_base_ptr>;
using fiber_ptr = std::unique_ptr<class fiber>;
// used by FIX8::fibers
struct f8_fibers
{
inline static int size() noexcept;
inline static int size_accurate() noexcept;
inline static int size_finished() noexcept;
inline static int size_detached() noexcept;
inline static bool has_fibers() noexcept;
inline static bool has_finished() noexcept;
inline static bool has_flag(global_fiber_flags flag) noexcept;
inline static void set_flag(global_fiber_flags flag) noexcept;
inline static void reset_flag(global_fiber_flags flag) noexcept;
inline static void sort() noexcept;
inline static void wait_all() noexcept;
inline static std::exception_ptr get_exception_ptr() noexcept;
template<std::invocable Fn>
static void wait_all(Fn&&) noexcept;
inline static bool terminating() noexcept;
inline static void wait_any() noexcept;
template<std::invocable Fn>
static void wait_any(Fn&&) noexcept;
#if defined FIX8_FIBER_INSTRUMENTATION_
inline static void print(std::ostream& os) noexcept;
#endif
inline static int kill_all() noexcept;
#if defined FIX8_FIBER_MULTITHREADING_
inline static void move(std::thread::id id, fiber_base_ptr ptr);
inline static void move(std::thread::id id, const class fiber& fb);
#endif
};
//-----------------------------------------------------------------------------------------
struct fiber_error : std::system_error
{
using std::system_error::system_error;
};
enum class launch { dispatch, post, none }; // from boost::fiber
//-----------------------------------------------------------------------------------------
/// ABC stack
class alignas(16) f8_stack
{
protected:
char *_ptr{};
std::size_t _size{FIX8_FIBER_DEFSTKSZ};
public:
constexpr f8_stack() noexcept = default;
virtual ~f8_stack() { deallocate(); }
f8_stack(f8_stack&&) noexcept = default;
f8_stack(f8_stack&) = delete;
f8_stack& operator=(f8_stack&) = delete;
virtual char *allocate(std::size_t size) = 0;
virtual void deallocate() noexcept { _ptr = nullptr; }
constexpr std::size_t size() const noexcept { return _size; }
#if defined FIX8_FIBER_INSTRUMENTATION_
friend std::ostream& operator<<(std::ostream& os, const f8_stack& what)
{
return os << reinterpret_cast<void *>(what._ptr) << ' ' << what._size;
}
#endif
};
using f8_stack_ptr = std::unique_ptr<f8_stack>;
//-----------------------------------------------------------------------------------------
/// Anonymous memory mapped stack
class f8_fixedsize_mapped_stack final : public f8_stack
{
public:
char *allocate(std::size_t size) override
{
if (!_ptr)
{
const auto PageSize { static_cast<size_t>(sysconf(_SC_PAGESIZE)) };
const std::size_t pages { (size + PageSize - 1) / PageSize }; // calculate pages required
_size = (pages + 1) * PageSize; // add a page at bottom for guard-page
if (void *vp { ::mmap(0, _size, PROT_READ | PROT_WRITE, MAP_PRIVATE |
#if defined(MAP_STACK)
MAP_ANON | MAP_STACK,
#elif defined(MAP_ANON)
MAP_ANON,
#else
MAP_ANONYMOUS,
#endif
-1, 0) }; vp == MAP_FAILED)
throw std::bad_alloc();
else
_ptr = static_cast<char *>(vp);
}
return _ptr;
}
void deallocate() noexcept override
{
if (_ptr)
::munmap(_ptr, _size);
f8_stack::deallocate();
}
};
//-----------------------------------------------------------------------------------------
/// Simple heap based stack
class f8_fixedsize_heap_stack final : public f8_stack
{
public:
char *allocate(std::size_t size) override
{
if (!_ptr)
{
_size = size & ~0xff;
_ptr = static_cast<char *>(::operator new(_size));
}
return _ptr;
}
void deallocate() noexcept override
{
delete _ptr;
f8_stack::deallocate();
}
};
//-----------------------------------------------------------------------------------------
/// Placement stack
class f8_fixedsize_placement_stack final : public f8_stack
{
public:
constexpr f8_fixedsize_placement_stack(char *top, size_t offs=0) noexcept { _ptr = top + offs; }
char *allocate(std::size_t size) noexcept override
{
_size = size;
return _ptr;
}
};
//-----------------------------------------------------------------------------------------
template<typename T=f8_fixedsize_heap_stack, typename... Args>
requires std::derived_from<T, f8_stack>
f8_stack_ptr make_stack(Args&&... args)
{
return f8_stack_ptr{new T(std::forward<Args>(args)...)};
}
enum class stack_type { heap, mapped, placement };
template<stack_type type, typename... Args>
f8_stack_ptr make_stack(Args&&... args)
{
using enum stack_type;
if constexpr (type == heap)
return make_stack(std::forward<Args>(args)...);
if constexpr (type == mapped)
return make_stack<f8_fixedsize_mapped_stack>(std::forward<Args>(args)...);
if constexpr (type == placement)
return make_stack<f8_fixedsize_placement_stack>(std::forward<Args>(args)...);
}
//-----------------------------------------------------------------------------------------
struct alignas(16) fiber_params final
{
const char name[FIX8_FIBER_FIBERNAMELEN]{};
int launch_order{99};
bool join{};
// these next values can't be modified once the fiber has been created
const size_t stacksz{FIX8_FIBER_DEFSTKSZ};
const launch policy{launch::post};
alignas(16) f8_stack_ptr stack{make_stack<stack_type::heap>()};
};
//-----------------------------------------------------------------------------------------
class alignas(64) fiber_base
{
uintptr_t *_stk; // top of fiber stack
const uintptr_t _stacksz;
uintptr_t *const _stk_alloc{}; // allocated stack memory
fiber_params _params;
const fiber_id _pfid; // parent fiber
#if defined FIX8_FIBER_INSTRUMENTATION_
fiber_id _prev_fiber;
unsigned _ctxswtchs{};
std::chrono::nanoseconds _extime{}, _exdelta{};
#endif
enum fiber_flags { main, finished, suspended, dispatched, detached, notstarted,
joinonexit, transfer, moved, fiber_flags_count }; // mfspdnjtv
std::bitset<fiber_flags_count> _flags;
std::chrono::steady_clock::time_point _tp{};
std::condition_variable _cv_join;
std::mutex _join_mutex;
template<typename Wrapper>
static void trampoline(void *ptr) noexcept;
// [asm] stack switch routine
static void coroswitch(fiber_base *old, fiber_base *newer) noexcept asm("_coroswitch");
static size_t get_default_stacksz()
{
static thread_local const auto sz([]()
{
size_t size{};
if (pthread_attr_t attr; pthread_attr_init(&attr) == 0)
pthread_attr_getstacksize(&attr, &size);
return size;
}());
return sz;
}
template<typename Fn>
struct callable_wrapper
{
std::decay_t<Fn> _func;
constexpr callable_wrapper(Fn&& func) noexcept : _func(std::forward<Fn>(func)) {}
};
// stack: trampoline,fiber(wrapper func),rdi,rbp,r12,r13,r14,r15,fpu/sse flags
// TODO: win64 xmm6 - xmm15
// TODO other architectures
template<typename Fn>
constexpr void setup_continuation(Fn&& func) noexcept
{
_stk = _stk_alloc + _stacksz / sizeof(uintptr_t) - 1; // set top of stack
*--_stk = reinterpret_cast<uintptr_t>(trampoline<callable_wrapper<Fn>>);
*--_stk = reinterpret_cast<uintptr_t>(new (reinterpret_cast<char*>(_stk_alloc) + sizeof(fiber_base))
callable_wrapper(std::forward<Fn>(func))); // store at bottom of stack
std::memset(_stk - 6, 0x0, 6 * sizeof(uintptr_t)); // zero: rdi,rbp,r12,r13,r14,r15
_stk -= 7; // include flags
asm("stmxcsr %0" : "=m" (*reinterpret_cast<uint32_t*>(_stk))); // preserve lower dword
asm("fnstcw %0" : "=m" (*(reinterpret_cast<uint32_t*>(_stk) + 1))); // preserve upper dword, lower word
}
fiber_base() noexcept : _stacksz{get_default_stacksz()},
_params{.name="main",.stacksz=_stacksz,.stack=f8_stack_ptr()},
#if defined FIX8_FIBER_INSTRUMENTATION_
_ctxswtchs{1},
#endif
_flags{1 << main} {}
public:
template<std::invocable Fn>
constexpr fiber_base(fiber_params&& params, Fn&& func, uintptr_t *sp, fiber_id parent) noexcept
: _stacksz(params.stacksz), _stk_alloc(sp), _params(std::move(params)), _pfid(parent),
_flags{(1 << notstarted) | (_params.join ? (1 << joinonexit) : 0ULL)}
{
setup_continuation(std::forward<Fn>(func));
}
~fiber_base() noexcept = default;
constexpr fiber_id get_id() const noexcept { return fiber_id(!is_main() ? this : nullptr); }
#if defined FIX8_FIBER_INSTRUMENTATION_
constexpr fiber_id get_prev_id() const noexcept { return _prev_fiber; }
std::string get_flags_as_string() const noexcept;
#endif
constexpr fiber_id get_pid() const noexcept { return _pfid; }
std::string_view name(std::string_view what) noexcept
{
if (!what.empty() && !is_main()) // you can't name main
{
const auto len { what.size() > FIX8_FIBER_FIBERNAMELEN - 1 ? FIX8_FIBER_FIBERNAMELEN - 1 : what.size() };
auto *ptr { const_cast<char*>(&_params.name[0]) }; // override const
std::memcpy(ptr, what.data(), len);
*(ptr + len) = 0;
}
return _params.name;
}
constexpr std::string_view name() const noexcept { return _params.name; }
int order(int ord) noexcept { return _params.launch_order = ord; }
constexpr bool joinable() const noexcept { return !_flags[finished]; };
constexpr bool is_main() const noexcept { return _flags[main]; };
constexpr bool is_detached() const noexcept { return _flags[detached]; };
constexpr bool is_suspended() const noexcept { return _flags[suspended]; };
constexpr bool is_joinonexit() const noexcept { return _flags[joinonexit]; };
constexpr bool is_dispatched() const noexcept { return _flags[dispatched]; };
constexpr bool is_transfering() const noexcept { return _flags[transfer]; };
constexpr bool is_moved() const noexcept { return _flags[moved]; };
#if defined FIX8_FIBER_INSTRUMENTATION_
friend std::ostream& operator<<(std::ostream& os, const fiber_base& what);
friend class fiber_monitor;
#endif
friend class fiber;
friend class jfiber;
friend f8_this_fiber;
friend f8_fibers;
};
//-----------------------------------------------------------------------------------------
// static void fiber_base::coroswitch(fiber_base *old, fiber_base *newer) noexcept; //aka _coroswitch
// TODO other architectures
asm(R"(.text
.align 16
.type _coroswitch,@function
_coroswitch:
cmpq %rdi,%rsi /* prevent self-switch */
jne _doswitch
ret
_doswitch:
subq $0x40,%rsp
stmxcsr (%rsp) /* save fpu/mx/sse flags */
fnstcw 4(%rsp)
movq %r15,8(%rsp)
movq %r14,8*2(%rsp)
movq %r13,8*3(%rsp)
movq %r12,8*4(%rsp)
movq %rbx,8*5(%rsp)
movq %rbp,8*6(%rsp)
movq %rdi,8*7(%rsp)
movq %rsp,(%rdi) /* save old user stack */
movq (%rsi),%rsp /* restore new user stack */
ldmxcsr (%rsp) /* restore fpu/mx/sse flags */
fldcw 4(%rsp)
movq 8(%rsp),%r15
movq 8*2(%rsp),%r14
movq 8*3(%rsp),%r13
movq 8*4(%rsp),%r12
movq 8*5(%rsp),%rbx
movq 8*6(%rsp),%rbp
movq 8*7(%rsp),%rdi
movq 8*8(%rsp),%r8 /* get ret address */
addq $0x48,%rsp /* one extra qword for ret */
jmp *%r8 /* jump to new location */
.size _coroswitch,.-_coroswitch
.section .note.GNU-stack,"",%progbits
)");
//-----------------------------------------------------------------------------------------
class alignas(16) fiber
{
using enum std::errc;
enum class exit_path { dtor, tramp };
fiber_base_ptr _ctx;
#define GetVars() auto& [uni, sch, cur, man, trm, now, flg, fin, ep] { fiber::get_vars() }
#define ConstGetVars() const GetVars()
#define GetVar(x) fiber::get_vars().x
#define ConstGetVar(x) static_cast<const decltype(fiber::cvars::x)&>(GetVar(x))
public:
struct alignas(64) cvars final
{
fiber_set _uniq;
fiber_queue _sched;
fiber_base_ptr _curr;
const fiber_base_ptr _main;
bool _term;
std::chrono::time_point<std::chrono::system_clock> _now;
std::bitset<static_cast<int>(global_fiber_flags::count)> _gflags;
int _finished;
std::exception_ptr _eptr;
~cvars() noexcept;
fiber_base_ptr operator[](unsigned idx) const noexcept { return idx < _sched.size() ? _sched[idx] : fiber_base_ptr(); }
size_t size() const noexcept { return _sched.size(); }
};
#if defined FIX8_FIBER_MULTITHREADING_
class alignas(64) all_cvars final
{
mutable f8_spin_lock _tvs_spl;
std::unordered_map<std::thread::id, cvars *> _tvs;
std::unordered_multimap<std::thread::id, fiber_base_ptr> _trf;
public:
all_cvars() noexcept = default;
all_cvars(const all_cvars&) = delete;
all_cvars(all_cvars&&) = delete;
all_cvars& operator=(const all_cvars&) = delete;
all_cvars& operator=(all_cvars&&) = delete;
size_t size() const
{
f8_scoped_spin_lock guard(_tvs_spl);
return _tvs.size();
}
size_t count() const
{
size_t result{};
f8_scoped_spin_lock guard(_tvs_spl);
for (const auto& pp : _tvs)
result += pp.second->size();
return result;
}
bool insert(std::thread::id id, cvars *var)
{
f8_scoped_spin_lock guard(_tvs_spl);
return _tvs.emplace(id, var).second;
}
bool remove(std::thread::id id)
{
f8_scoped_spin_lock guard(_tvs_spl);
return _tvs.erase(id) > 0;
}
cvars *get(std::thread::id id) // ptr is not thread safe
{
f8_scoped_spin_lock guard(_tvs_spl);
auto result { _tvs.find(id) };
return result != _tvs.end() ? result->second : nullptr;
}
const cvars *get(std::thread::id id) const // ptr is not thread safe
{
f8_scoped_spin_lock guard(_tvs_spl);
auto result { _tvs.find(id) };
return result != _tvs.cend() ? result->second : nullptr;
}
void queue_move(std::thread::id id, fiber_base_ptr ptr) // transfer from this thread to other thread
{
if (id == std::this_thread::get_id())
throw fiber_error { std::make_error_code(invalid_argument),
"target thread same as source thread" };
else if (!ptr)
throw fiber_error { std::make_error_code(invalid_argument),
"invalid fiber" };
else if (id == std::thread::id()) // empty id
throw fiber_error { std::make_error_code(invalid_argument),
"invalid id" };
else if (f8_scoped_spin_lock guard(_tvs_spl); _tvs.find(id) != _tvs.cend())
{
ptr->_flags.set(fiber_base::transfer);
GetVar(_uniq).erase(ptr);
_trf.emplace(id, ptr);
guard.release();
f8_this_fiber::yield();
}
/*else
throw fiber_error { std::make_error_code(invalid_argument),
"thread not running" };*/
}
int move() // process transfers to this thread
{
int result{};
f8_scoped_spin_lock guard(_tvs_spl);
if (auto rng { _trf.equal_range(std::this_thread::get_id()) }; rng.first != rng.second)
{
GetVars();
do
{
uni.insert(rng.first->second);
sch.push_back(rng.first->second);
++result;
}
while (++rng.first != rng.second);
sort_queue(sch);
_trf.erase(std::this_thread::get_id());
}
return result;
}
};
#endif
private:
#if defined FIX8_FIBER_MULTITHREADING_
static all_cvars& get_all_cvars() noexcept
{
static all_cvars _allcvars; // per process singleton
return _allcvars;
}
#endif
static cvars& get_vars() noexcept
{
static thread_local fiber_base _main_ctx;
static thread_local fiber_base_ptr _main_ctx_ptr { fiber_base_ptr(&_main_ctx, [](auto *) {}) };
static thread_local cvars _cvars // per thread singleton
{
._uniq={_main_ctx_ptr},._curr=_main_ctx_ptr,._main=_main_ctx_ptr,
._term=false,._now=std::chrono::system_clock::now()
};
#if defined FIX8_FIBER_MULTITHREADING_
static thread_local bool _register_cvars([]() // register this thread
{
return get_all_cvars().insert(std::this_thread::get_id(), &_cvars);
}());
#endif
return _cvars;
}
static void fiber_exit(exit_path epath)
{
std::ostringstream eostr;
#if defined FIX8_FIBER_INSTRUMENTATION_
if (!f8_this_fiber::name().empty())
eostr << std::quoted(f8_this_fiber::name(), '\'');
else
#endif
eostr << "fiber";
#if defined FIX8_FIBER_INSTRUMENTATION_
if (f8_this_fiber::get_id())
eostr << " (fid=" << f8_this_fiber::get_id() << ')';
#endif
eostr << " has exited (" << (epath == exit_path::dtor ? "dtor" : "trampoline") << ").";
if (!f8_fibers::has_flag(global_fiber_flags::termthrow))
{
std::cerr << eostr.str() << " Terminating application." << std::endl;
std::terminate();
}
if (f8_fibers::has_flag(global_fiber_flags::excepthandling))
GetVar(_eptr) = std::make_exception_ptr(std::logic_error(eostr.str()));
}
static void sort_queue(fiber_queue& sch) noexcept
{
std::stable_sort(sch.begin(), sch.end(), [](const fiber_base_ptr& p1, const fiber_base_ptr& p2)
{
return p1->_params.launch_order < p2->_params.launch_order;
});
}
public:
template<typename Fn, typename... Args>
requires std::invocable<Fn, Args...> && (!std::is_bind_expression_v<Fn>)
constexpr fiber(Fn&& func, Args&&... args)
: fiber({}, std::bind(std::forward<Fn>(func), std::forward<Args>(args)...)) {}
template<typename Fn, typename... Args>
requires std::invocable<Fn, Args...> && (!std::is_bind_expression_v<Fn>)
constexpr fiber(fiber_params&& params, Fn&& func, Args&&... args)
: fiber(std::forward<fiber_params>(params), std::bind(std::forward<Fn>(func), std::forward<Args>(args)...)) {}
template<std::invocable Fn>
constexpr fiber(Fn&& func) : fiber({}, std::forward<Fn>(func)) {}
template<std::invocable Fn>
constexpr fiber(fiber_params&& params, Fn&& func)
{
uintptr_t *sp { reinterpret_cast<uintptr_t *>(params.stack->allocate(params.stacksz)) };
GetVars();
reset(new (reinterpret_cast<char*>(sp))
fiber_base(std::forward<fiber_params>(params), std::forward<Fn>(func), sp, cur->get_id()), [](auto *) {});
uni.insert(_ctx);
sch.push_back(_ctx);
sort_queue(sch);
if (_ctx->_params.policy == launch::dispatch)
{
_ctx->_flags.set(fiber_base::dispatched);
resume();
}
}
fiber(const fiber&) = delete;
fiber& operator=(const fiber&) = delete;
~fiber()
{
if (_ctx)
{
if (joinable() && !is_detached() && !is_moved() && !is_transfering())
{
if (is_joinonexit())
join();
else
fiber_exit(exit_path::dtor);
}
else if (is_moved())
_ctx->_flags.reset(fiber_base::moved);
}
}
fiber(fiber_base_ptr from) noexcept : _ctx(std::move(from)) {}
fiber(fiber&& other) noexcept
{
*this = std::move(other);
}
fiber& operator=(fiber&& other) noexcept
{
_ctx = std::move(other._ctx);
return *this;
}
fiber& set_joinonexit(bool set=true) noexcept
{
(_ctx->_params.join = set) ? _ctx->_flags.set(fiber_base::joinonexit)
: _ctx->_flags.reset(fiber_base::joinonexit);
return *this;
}
fiber& set_params(std::string_view nm, int lo=99, bool jn=false) noexcept
{
name(nm);
order(lo);
set_joinonexit(jn);
return *this;
}
void join()
{
if (auto& cur { GetVar(_curr) }; _ctx != cur)
{
if (!joinable())
throw fiber_error { std::make_error_code(invalid_argument),
"fiber not joinable" };
else
{
std::unique_lock jlock(_ctx->_join_mutex);
_ctx->_cv_join.wait(jlock, [this]
{
f8_this_fiber::yield();
return !joinable();
});
}
}
else
throw fiber_error { std::make_error_code(resource_deadlock_would_occur),
"fiber cannot self-join" };
}
void join_if()
{
if (joinable())
join();
}
void detach()
{
if (is_detached())
throw fiber_error { std::make_error_code(invalid_argument),
"fiber already detached" };
else if (!joinable() && !is_dispatched())
throw fiber_error { std::make_error_code(invalid_argument),
"fiber not joinable" };
else
_ctx->_flags.set(fiber_base::fiber_flags::detached);
}
void suspend()
{
if (!joinable())
throw fiber_error { std::make_error_code(invalid_argument),
"fiber not joinable" };
else if (is_detached())
throw fiber_error { std::make_error_code(invalid_argument),
"cannot suspend detached fiber" };
else if (is_suspended())
throw fiber_error { std::make_error_code(invalid_argument),
"fiber already suspended" };
_ctx->_tp = decltype(_ctx->_tp){};
_ctx->_flags.set(fiber_base::suspended);
}
void unsuspend()
{
if (!joinable())
throw fiber_error { std::make_error_code(invalid_argument),
"fiber not joinable" };
else if (is_detached())
throw fiber_error { std::make_error_code(invalid_argument),
"cannot unsuspend detached fiber" };
else if (!is_suspended())
throw fiber_error { std::make_error_code(invalid_argument),
"fiber not suspended" };
_ctx->_tp = decltype(_ctx->_tp){};
_ctx->_flags.reset(fiber_base::suspended);
}
void kill()
{
if (!joinable())
throw fiber_error { std::make_error_code(invalid_argument),
"fiber not joinable" };
else if (is_detached())
throw fiber_error { std::make_error_code(invalid_argument),
"cannot kill detached fiber" };
_ctx->_flags.set(fiber_base::finished); // will not be scheduled again
++GetVar(_finished);
}
bool schedule(bool check=true)
{
if (check)
{
if (!joinable())
throw fiber_error { std::make_error_code(invalid_argument),
"fiber not joinable" };
else if (is_detached())
throw fiber_error { std::make_error_code(invalid_argument),
"cannot schedule detached fiber" };
}
GetVars();
if (cur == _ctx)
throw fiber_error { std::make_error_code(resource_deadlock_would_occur),
"fiber cannot schedule itself" };
else if (uni.contains(_ctx))
{
if (auto& front { sch.front() }; front != _ctx)
{
for (auto itr { sch.begin() }; itr != sch.end(); ++itr)
{
if (*itr == _ctx)
{
itr->swap(front); // swap next with specified fiber
break;
}
}
}
return true;
}
return false;
}
void resume(bool check=true)
{
if (schedule(check))
f8_this_fiber::yield();
}
void resume_if()
{
if (joinable() && !is_detached())
resume(false);
}
bool schedule_if()
{
return joinable() && !is_detached() ? schedule(false) : false;
}
template<typename Fn, typename... Args>
requires std::invocable<Fn, Args...> && (!std::is_bind_expression_v<Fn>)
constexpr void resume_with(Fn&& func, Args&&... args)
{ resume_with(std::bind(std::forward<Fn>(func), std::forward<Args>(args)...)); }
template<std::invocable Fn>
void resume_with(Fn&& func)
{
_ctx->setup_continuation(std::forward<Fn>(func));
resume();
}
#if defined FIX8_FIBER_MULTITHREADING_
void move(std::thread::id id)
{
get_all_cvars().queue_move(id, _ctx);
}
#endif
void swap(fiber& other) noexcept
{
if (_ctx != other._ctx)
_ctx.swap(other._ctx);
}
void reset() noexcept
{
_ctx.reset();
}
template<typename Y, typename Deleter>
void reset(Y* ptr, Deleter d) noexcept
{
_ctx.reset(ptr, d);
}
static void sort() noexcept
{
sort_queue(GetVar(_sched));
}
#if defined FIX8_FIBER_INSTRUMENTATION_
static const cvars& const_get_vars() noexcept { return get_vars(); }
#if defined FIX8_FIBER_MULTITHREADING_
static const all_cvars& const_get_all_cvars() noexcept { return get_all_cvars(); }
#endif
#endif
bool joinable() const noexcept { return _ctx->joinable(); }
bool is_main() const noexcept { return _ctx->is_main(); }
bool is_detached() const noexcept { return _ctx->is_detached(); }
bool is_suspended() const noexcept { return _ctx->is_suspended(); };
bool is_joinonexit() const noexcept { return _ctx->is_joinonexit(); }
bool is_dispatched() const noexcept { return _ctx->is_dispatched(); }
bool is_transfering() const noexcept { return _ctx->is_transfering(); }
bool is_moved() const noexcept { return _ctx->is_moved(); }
explicit operator bool() const noexcept { return joinable(); }
bool operator! () const noexcept { return !joinable(); }
std::string_view name(std::string_view what) noexcept { return _ctx->name(what); }
std::string_view name() const noexcept { return _ctx->name(); }
int order(int ord=99) noexcept { return ord == 99 ? _ctx->_params.launch_order : _ctx->_params.launch_order = ord; }
fiber_id get_id() const noexcept { return _ctx->get_id(); }
fiber_id get_pid() const noexcept { return _ctx->get_pid(); }
fiber_base_ptr get_ctx() noexcept { return _ctx; }
#if defined FIX8_FIBER_INSTRUMENTATION_
fiber_id get_prev_id() const noexcept { return _ctx->get_prev_id(); }
int get_ctxswtchs() const noexcept { return _ctx->_ctxswtchs; }
friend std::ostream& operator<<(std::ostream& os, const fiber_base& what);
friend std::ostream& operator<<(std::ostream& os, const fiber& what) { return os << *what._ctx; }
#endif
friend f8_this_fiber;
friend f8_fibers;
friend fiber_base;
friend class jfiber;
};
inline void swap(fiber& first, fiber& second) noexcept
{
first.swap(second);
}
inline bool operator<(const fiber& left, const fiber& right) noexcept
{
return left.get_id() < right.get_id();
}
//-----------------------------------------------------------------------------------------
class jfiber : public fiber
{
public:
template<typename Fn, typename... Args>
requires std::invocable<Fn, Args...> && (!std::is_bind_expression_v<Fn>)
constexpr jfiber(Fn&& func, Args&&... args)
: fiber({.join=true}, std::bind(std::forward<Fn>(func), std::forward<Args>(args)...)) {}
template<typename Fn, typename... Args>
requires std::invocable<Fn, Args...> && (!std::is_bind_expression_v<Fn>)
constexpr jfiber(fiber_params&& params, Fn&& func, Args&&... args)