-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathflow_graph.h
3733 lines (3188 loc) · 140 KB
/
flow_graph.h
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
/*
Copyright (c) 2005-2025 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __TBB_flow_graph_H
#define __TBB_flow_graph_H
#include <atomic>
#include <memory>
#include <type_traits>
#include "detail/_config.h"
#include "detail/_namespace_injection.h"
#include "spin_mutex.h"
#include "null_mutex.h"
#include "spin_rw_mutex.h"
#include "null_rw_mutex.h"
#include "detail/_pipeline_filters.h"
#include "detail/_task.h"
#include "detail/_small_object_pool.h"
#include "cache_aligned_allocator.h"
#include "detail/_exception.h"
#include "detail/_template_helpers.h"
#include "detail/_aggregator.h"
#include "detail/_allocator_traits.h"
#include "detail/_utils.h"
#include "profiling.h"
#include "task_arena.h"
#if TBB_USE_PROFILING_TOOLS && ( __unix__ || __APPLE__ )
#if __INTEL_COMPILER
// Disabled warning "routine is both inline and noinline"
#pragma warning (push)
#pragma warning( disable: 2196 )
#endif
#define __TBB_NOINLINE_SYM __attribute__((noinline))
#else
#define __TBB_NOINLINE_SYM
#endif
#include <tuple>
#include <list>
#include <forward_list>
#include <queue>
#if __TBB_CPP20_CONCEPTS_PRESENT
#include <concepts>
#endif
/** @file
\brief The graph related classes and functions
There are some applications that best express dependencies as messages
passed between nodes in a graph. These messages may contain data or
simply act as signals that a predecessors has completed. The graph
class and its associated node classes can be used to express such
applications.
*/
namespace tbb {
namespace detail {
namespace d2 {
//! An enumeration the provides the two most common concurrency levels: unlimited and serial
enum concurrency { unlimited = 0, serial = 1 };
//! A generic null type
struct null_type {};
//! An empty class used for messages that mean "I'm done"
class continue_msg {};
} // namespace d2
#if __TBB_CPP20_CONCEPTS_PRESENT
namespace d0 {
template <typename ReturnType, typename OutputType>
concept node_body_return_type = std::same_as<OutputType, tbb::detail::d2::continue_msg> ||
std::convertible_to<OutputType, ReturnType>;
// TODO: consider using std::invocable here
template <typename Body, typename Output>
concept continue_node_body = std::copy_constructible<Body> &&
requires( Body& body, const tbb::detail::d2::continue_msg& v ) {
{ body(v) } -> node_body_return_type<Output>;
};
template <typename Body, typename Input, typename Output>
concept function_node_body = std::copy_constructible<Body> &&
std::invocable<Body&, const Input&> &&
node_body_return_type<std::invoke_result_t<Body&, const Input&>, Output>;
template <typename FunctionObject, typename Input, typename Key>
concept join_node_function_object = std::copy_constructible<FunctionObject> &&
std::invocable<FunctionObject&, const Input&> &&
std::convertible_to<std::invoke_result_t<FunctionObject&, const Input&>, Key>;
template <typename Body, typename Output>
concept input_node_body = std::copy_constructible<Body> &&
requires( Body& body, tbb::detail::d1::flow_control& fc ) {
{ body(fc) } -> adaptive_same_as<Output>;
};
template <typename Body, typename Input, typename OutputPortsType>
concept multifunction_node_body = std::copy_constructible<Body> &&
std::invocable<Body&, const Input&, OutputPortsType&>;
template <typename Sequencer, typename Value>
concept sequencer = std::copy_constructible<Sequencer> &&
std::invocable<Sequencer&, const Value&> &&
std::convertible_to<std::invoke_result_t<Sequencer&, const Value&>, std::size_t>;
template <typename Body, typename Input, typename GatewayType>
concept async_node_body = std::copy_constructible<Body> &&
std::invocable<Body&, const Input&, GatewayType&>;
} // namespace d0
#endif // __TBB_CPP20_CONCEPTS_PRESENT
namespace d2 {
//! Forward declaration section
template< typename T > class sender;
template< typename T > class receiver;
class continue_receiver;
template< typename T, typename U > class limiter_node; // needed for resetting decrementer
template<typename T, typename M> class successor_cache;
template<typename T, typename M> class broadcast_cache;
template<typename T, typename M> class round_robin_cache;
template<typename T, typename M> class predecessor_cache;
template<typename T, typename M> class reservable_predecessor_cache;
#if __TBB_PREVIEW_FLOW_GRAPH_NODE_SET
namespace order {
struct following;
struct preceding;
}
template<typename Order, typename... Args> struct node_set;
#endif
} // namespace d2
} // namespace detail
} // namespace tbb
//! The graph class
#include "detail/_flow_graph_impl.h"
namespace tbb {
namespace detail {
namespace d2 {
static inline std::pair<graph_task*, graph_task*> order_tasks(graph_task* first, graph_task* second) {
if (second->priority > first->priority)
return std::make_pair(second, first);
return std::make_pair(first, second);
}
// submit task if necessary. Returns the non-enqueued task if there is one.
static inline graph_task* combine_tasks(graph& g, graph_task* left, graph_task* right) {
// if no RHS task, don't change left.
if (right == nullptr) return left;
// right != nullptr
if (left == nullptr) return right;
if (left == SUCCESSFULLY_ENQUEUED) return right;
// left contains a task
if (right != SUCCESSFULLY_ENQUEUED) {
// both are valid tasks
auto tasks_pair = order_tasks(left, right);
spawn_in_graph_arena(g, *tasks_pair.first);
return tasks_pair.second;
}
return left;
}
#if __TBB_PREVIEW_FLOW_GRAPH_TRY_PUT_AND_WAIT
class message_metainfo {
public:
using waiters_type = std::forward_list<d1::wait_context_vertex*>;
message_metainfo() = default;
message_metainfo(const waiters_type& waiters) : my_waiters(waiters) {}
message_metainfo(waiters_type&& waiters) : my_waiters(std::move(waiters)) {}
const waiters_type& waiters() const & { return my_waiters; }
waiters_type&& waiters() && { return std::move(my_waiters); }
bool empty() const { return my_waiters.empty(); }
void merge(const message_metainfo& other) {
// TODO: should we avoid duplications on merging
my_waiters.insert_after(my_waiters.before_begin(),
other.waiters().begin(),
other.waiters().end());
}
private:
waiters_type my_waiters;
}; // class message_metainfo
#define __TBB_FLOW_GRAPH_METAINFO_ARG(metainfo) , metainfo
#else
#define __TBB_FLOW_GRAPH_METAINFO_ARG(metainfo)
#endif // __TBB_PREVIEW_FLOW_GRAPH_TRY_PUT_AND_WAIT
//! Pure virtual template class that defines a sender of messages of type T
template< typename T >
class sender {
public:
virtual ~sender() {}
//! Request an item from the sender
virtual bool try_get( T & ) { return false; }
#if __TBB_PREVIEW_FLOW_GRAPH_TRY_PUT_AND_WAIT
virtual bool try_get( T &, message_metainfo& ) { return false; }
#endif
//! Reserves an item in the sender
virtual bool try_reserve( T & ) { return false; }
#if __TBB_PREVIEW_FLOW_GRAPH_TRY_PUT_AND_WAIT
virtual bool try_reserve( T &, message_metainfo& ) { return false; }
#endif
//! Releases the reserved item
virtual bool try_release( ) { return false; }
//! Consumes the reserved item
virtual bool try_consume( ) { return false; }
protected:
//! The output type of this sender
typedef T output_type;
//! The successor type for this node
typedef receiver<T> successor_type;
//! Add a new successor to this node
virtual bool register_successor( successor_type &r ) = 0;
//! Removes a successor from this node
virtual bool remove_successor( successor_type &r ) = 0;
template<typename C>
friend bool register_successor(sender<C>& s, receiver<C>& r);
template<typename C>
friend bool remove_successor (sender<C>& s, receiver<C>& r);
}; // class sender<T>
template<typename C>
bool register_successor(sender<C>& s, receiver<C>& r) {
return s.register_successor(r);
}
template<typename C>
bool remove_successor(sender<C>& s, receiver<C>& r) {
return s.remove_successor(r);
}
//! Pure virtual template class that defines a receiver of messages of type T
template< typename T >
class receiver {
private:
template <typename... TryPutTaskArgs>
bool internal_try_put(const T& t, TryPutTaskArgs&&... args) {
graph_task* res = try_put_task(t, std::forward<TryPutTaskArgs>(args)...);
if (!res) return false;
if (res != SUCCESSFULLY_ENQUEUED) spawn_in_graph_arena(graph_reference(), *res);
return true;
}
public:
//! Destructor
virtual ~receiver() {}
//! Put an item to the receiver
bool try_put( const T& t ) {
return internal_try_put(t);
}
#if __TBB_PREVIEW_FLOW_GRAPH_TRY_PUT_AND_WAIT
//! Put an item to the receiver and wait for completion
bool try_put_and_wait( const T& t ) {
// Since try_put_and_wait is a blocking call, it is safe to create wait_context on stack
d1::wait_context_vertex msg_wait_vertex{};
bool res = internal_try_put(t, message_metainfo{message_metainfo::waiters_type{&msg_wait_vertex}});
if (res) {
__TBB_ASSERT(graph_reference().my_context != nullptr, "No wait_context associated with the Flow Graph");
d1::wait(msg_wait_vertex.get_context(), *graph_reference().my_context);
}
return res;
}
#endif
//! put item to successor; return task to run the successor if possible.
protected:
//! The input type of this receiver
typedef T input_type;
//! The predecessor type for this node
typedef sender<T> predecessor_type;
template< typename R, typename B > friend class run_and_put_task;
template< typename X, typename Y > friend class broadcast_cache;
template< typename X, typename Y > friend class round_robin_cache;
virtual graph_task *try_put_task(const T& t) = 0;
#if __TBB_PREVIEW_FLOW_GRAPH_TRY_PUT_AND_WAIT
virtual graph_task *try_put_task(const T& t, const message_metainfo&) = 0;
#endif
virtual graph& graph_reference() const = 0;
template<typename TT, typename M> friend class successor_cache;
virtual bool is_continue_receiver() { return false; }
// TODO revamp: reconsider the inheritance and move node priority out of receiver
virtual node_priority_t priority() const { return no_priority; }
//! Add a predecessor to the node
virtual bool register_predecessor( predecessor_type & ) { return false; }
//! Remove a predecessor from the node
virtual bool remove_predecessor( predecessor_type & ) { return false; }
template <typename C>
friend bool register_predecessor(receiver<C>& r, sender<C>& s);
template <typename C>
friend bool remove_predecessor (receiver<C>& r, sender<C>& s);
}; // class receiver<T>
template <typename C>
bool register_predecessor(receiver<C>& r, sender<C>& s) {
return r.register_predecessor(s);
}
template <typename C>
bool remove_predecessor(receiver<C>& r, sender<C>& s) {
return r.remove_predecessor(s);
}
//! Base class for receivers of completion messages
/** These receivers automatically reset, but cannot be explicitly waited on */
class continue_receiver : public receiver< continue_msg > {
protected:
//! Constructor
explicit continue_receiver( int number_of_predecessors, node_priority_t a_priority ) {
my_predecessor_count = my_initial_predecessor_count = number_of_predecessors;
my_current_count = 0;
my_priority = a_priority;
}
//! Copy constructor
continue_receiver( const continue_receiver& src ) : receiver<continue_msg>() {
my_predecessor_count = my_initial_predecessor_count = src.my_initial_predecessor_count;
my_current_count = 0;
my_priority = src.my_priority;
}
//! Increments the trigger threshold
bool register_predecessor( predecessor_type & ) override {
spin_mutex::scoped_lock l(my_mutex);
++my_predecessor_count;
return true;
}
//! Decrements the trigger threshold
/** Does not check to see if the removal of the predecessor now makes the current count
exceed the new threshold. So removing a predecessor while the graph is active can cause
unexpected results. */
bool remove_predecessor( predecessor_type & ) override {
spin_mutex::scoped_lock l(my_mutex);
--my_predecessor_count;
return true;
}
//! The input type
typedef continue_msg input_type;
//! The predecessor type for this node
typedef receiver<input_type>::predecessor_type predecessor_type;
template< typename R, typename B > friend class run_and_put_task;
template<typename X, typename Y> friend class broadcast_cache;
template<typename X, typename Y> friend class round_robin_cache;
private:
// execute body is supposed to be too small to create a task for.
graph_task* try_put_task_impl( const input_type& __TBB_FLOW_GRAPH_METAINFO_ARG(const message_metainfo& metainfo) ) {
#if __TBB_PREVIEW_FLOW_GRAPH_TRY_PUT_AND_WAIT
message_metainfo predecessor_metainfo;
#endif
{
spin_mutex::scoped_lock l(my_mutex);
#if __TBB_PREVIEW_FLOW_GRAPH_TRY_PUT_AND_WAIT
// Prolong the wait and store the metainfo until receiving signals from all the predecessors
for (auto waiter : metainfo.waiters()) {
waiter->reserve(1);
}
my_current_metainfo.merge(metainfo);
#endif
if ( ++my_current_count < my_predecessor_count )
return SUCCESSFULLY_ENQUEUED;
else {
my_current_count = 0;
#if __TBB_PREVIEW_FLOW_GRAPH_TRY_PUT_AND_WAIT
predecessor_metainfo = my_current_metainfo;
my_current_metainfo = message_metainfo{};
#endif
}
}
#if __TBB_PREVIEW_FLOW_GRAPH_TRY_PUT_AND_WAIT
graph_task* res = execute(predecessor_metainfo);
for (auto waiter : predecessor_metainfo.waiters()) {
waiter->release(1);
}
#else
graph_task* res = execute();
#endif
return res? res : SUCCESSFULLY_ENQUEUED;
}
protected:
graph_task* try_put_task( const input_type& input ) override {
return try_put_task_impl(input __TBB_FLOW_GRAPH_METAINFO_ARG(message_metainfo{}));
}
#if __TBB_PREVIEW_FLOW_GRAPH_TRY_PUT_AND_WAIT
graph_task* try_put_task( const input_type& input, const message_metainfo& metainfo ) override {
return try_put_task_impl(input, metainfo);
}
#endif
spin_mutex my_mutex;
int my_predecessor_count;
int my_current_count;
int my_initial_predecessor_count;
#if __TBB_PREVIEW_FLOW_GRAPH_TRY_PUT_AND_WAIT
message_metainfo my_current_metainfo;
#endif
node_priority_t my_priority;
// the friend declaration in the base class did not eliminate the "protected class"
// error in gcc 4.1.2
template<typename U, typename V> friend class limiter_node;
virtual void reset_receiver( reset_flags f ) {
my_current_count = 0;
if (f & rf_clear_edges) {
my_predecessor_count = my_initial_predecessor_count;
}
}
//! Does whatever should happen when the threshold is reached
/** This should be very fast or else spawn a task. This is
called while the sender is blocked in the try_put(). */
#if __TBB_PREVIEW_FLOW_GRAPH_TRY_PUT_AND_WAIT
virtual graph_task* execute(const message_metainfo& metainfo) = 0;
#else
virtual graph_task* execute() = 0;
#endif
template<typename TT, typename M> friend class successor_cache;
bool is_continue_receiver() override { return true; }
node_priority_t priority() const override { return my_priority; }
}; // class continue_receiver
#if __TBB_PREVIEW_MESSAGE_BASED_KEY_MATCHING
template <typename K, typename T>
K key_from_message( const T &t ) {
return t.key();
}
#endif /* __TBB_PREVIEW_MESSAGE_BASED_KEY_MATCHING */
} // d1
} // detail
} // tbb
#include "detail/_flow_graph_trace_impl.h"
#include "detail/_hash_compare.h"
namespace tbb {
namespace detail {
namespace d2 {
#include "detail/_flow_graph_body_impl.h"
#include "detail/_flow_graph_cache_impl.h"
#include "detail/_flow_graph_types_impl.h"
using namespace graph_policy_namespace;
template <typename C, typename N>
graph_iterator<C,N>::graph_iterator(C *g, bool begin) : my_graph(g), current_node(nullptr)
{
if (begin) current_node = my_graph->my_nodes;
//else it is an end iterator by default
}
template <typename C, typename N>
typename graph_iterator<C,N>::reference graph_iterator<C,N>::operator*() const {
__TBB_ASSERT(current_node, "graph_iterator at end");
return *operator->();
}
template <typename C, typename N>
typename graph_iterator<C,N>::pointer graph_iterator<C,N>::operator->() const {
return current_node;
}
template <typename C, typename N>
void graph_iterator<C,N>::internal_forward() {
if (current_node) current_node = current_node->next;
}
//! Constructs a graph with isolated task_group_context
inline graph::graph() : my_wait_context_vertex(0), my_nodes(nullptr), my_nodes_last(nullptr), my_task_arena(nullptr) {
prepare_task_arena();
own_context = true;
cancelled = false;
caught_exception = false;
my_context = new (r1::cache_aligned_allocate(sizeof(task_group_context))) task_group_context(FLOW_TASKS);
fgt_graph(this);
my_is_active = true;
}
inline graph::graph(task_group_context& use_this_context) :
my_wait_context_vertex(0), my_context(&use_this_context), my_nodes(nullptr), my_nodes_last(nullptr), my_task_arena(nullptr) {
prepare_task_arena();
own_context = false;
cancelled = false;
caught_exception = false;
fgt_graph(this);
my_is_active = true;
}
inline graph::~graph() {
wait_for_all();
if (own_context) {
my_context->~task_group_context();
r1::cache_aligned_deallocate(my_context);
}
delete my_task_arena;
}
inline void graph::reserve_wait() {
my_wait_context_vertex.reserve();
fgt_reserve_wait(this);
}
inline void graph::release_wait() {
fgt_release_wait(this);
my_wait_context_vertex.release();
}
inline void graph::register_node(graph_node *n) {
n->next = nullptr;
{
spin_mutex::scoped_lock lock(nodelist_mutex);
n->prev = my_nodes_last;
if (my_nodes_last) my_nodes_last->next = n;
my_nodes_last = n;
if (!my_nodes) my_nodes = n;
}
}
inline void graph::remove_node(graph_node *n) {
{
spin_mutex::scoped_lock lock(nodelist_mutex);
__TBB_ASSERT(my_nodes && my_nodes_last, "graph::remove_node: Error: no registered nodes");
if (n->prev) n->prev->next = n->next;
if (n->next) n->next->prev = n->prev;
if (my_nodes_last == n) my_nodes_last = n->prev;
if (my_nodes == n) my_nodes = n->next;
}
n->prev = n->next = nullptr;
}
inline void graph::reset( reset_flags f ) {
// reset context
deactivate_graph(*this);
my_context->reset();
cancelled = false;
caught_exception = false;
// reset all the nodes comprising the graph
for(iterator ii = begin(); ii != end(); ++ii) {
graph_node *my_p = &(*ii);
my_p->reset_node(f);
}
// Reattach the arena. Might be useful to run the graph in a particular task_arena
// while not limiting graph lifetime to a single task_arena::execute() call.
prepare_task_arena( /*reinit=*/true );
activate_graph(*this);
}
inline void graph::cancel() {
my_context->cancel_group_execution();
}
inline graph::iterator graph::begin() { return iterator(this, true); }
inline graph::iterator graph::end() { return iterator(this, false); }
inline graph::const_iterator graph::begin() const { return const_iterator(this, true); }
inline graph::const_iterator graph::end() const { return const_iterator(this, false); }
inline graph::const_iterator graph::cbegin() const { return const_iterator(this, true); }
inline graph::const_iterator graph::cend() const { return const_iterator(this, false); }
inline graph_node::graph_node(graph& g) : my_graph(g) {
my_graph.register_node(this);
}
inline graph_node::~graph_node() {
my_graph.remove_node(this);
}
#include "detail/_flow_graph_node_impl.h"
//! An executable node that acts as a source, i.e. it has no predecessors
template < typename Output >
__TBB_requires(std::copyable<Output>)
class input_node : public graph_node, public sender< Output > {
public:
//! The type of the output message, which is complete
typedef Output output_type;
//! The type of successors of this node
typedef typename sender<output_type>::successor_type successor_type;
// Input node has no input type
typedef null_type input_type;
//! Constructor for a node with a successor
template< typename Body >
__TBB_requires(input_node_body<Body, Output>)
__TBB_NOINLINE_SYM input_node( graph &g, Body body )
: graph_node(g), my_active(false)
, my_body( new input_body_leaf< output_type, Body>(body) )
, my_init_body( new input_body_leaf< output_type, Body>(body) )
, my_successors(this), my_reserved(false), my_has_cached_item(false)
{
fgt_node_with_body(CODEPTR(), FLOW_INPUT_NODE, &this->my_graph,
static_cast<sender<output_type> *>(this), this->my_body);
}
#if __TBB_PREVIEW_FLOW_GRAPH_NODE_SET
template <typename Body, typename... Successors>
__TBB_requires(input_node_body<Body, Output>)
input_node( const node_set<order::preceding, Successors...>& successors, Body body )
: input_node(successors.graph_reference(), body)
{
make_edges(*this, successors);
}
#endif
//! Copy constructor
__TBB_NOINLINE_SYM input_node( const input_node& src )
: graph_node(src.my_graph), sender<Output>()
, my_active(false)
, my_body(src.my_init_body->clone()), my_init_body(src.my_init_body->clone())
, my_successors(this), my_reserved(false), my_has_cached_item(false)
{
fgt_node_with_body(CODEPTR(), FLOW_INPUT_NODE, &this->my_graph,
static_cast<sender<output_type> *>(this), this->my_body);
}
//! The destructor
~input_node() { delete my_body; delete my_init_body; }
//! Add a new successor to this node
bool register_successor( successor_type &r ) override {
spin_mutex::scoped_lock lock(my_mutex);
my_successors.register_successor(r);
if ( my_active )
spawn_put();
return true;
}
//! Removes a successor from this node
bool remove_successor( successor_type &r ) override {
spin_mutex::scoped_lock lock(my_mutex);
my_successors.remove_successor(r);
return true;
}
//! Request an item from the node
bool try_get( output_type &v ) override {
spin_mutex::scoped_lock lock(my_mutex);
if ( my_reserved )
return false;
if ( my_has_cached_item ) {
v = my_cached_item;
my_has_cached_item = false;
return true;
}
// we've been asked to provide an item, but we have none. enqueue a task to
// provide one.
if ( my_active )
spawn_put();
return false;
}
//! Reserves an item.
bool try_reserve( output_type &v ) override {
spin_mutex::scoped_lock lock(my_mutex);
if ( my_reserved ) {
return false;
}
if ( my_has_cached_item ) {
v = my_cached_item;
my_reserved = true;
return true;
} else {
return false;
}
}
#if __TBB_PREVIEW_FLOW_GRAPH_TRY_PUT_AND_WAIT
private:
bool try_reserve( output_type& v, message_metainfo& ) override {
return try_reserve(v);
}
bool try_get( output_type& v, message_metainfo& ) override {
return try_get(v);
}
public:
#endif
//! Release a reserved item.
/** true = item has been released and so remains in sender, dest must request or reserve future items */
bool try_release( ) override {
spin_mutex::scoped_lock lock(my_mutex);
__TBB_ASSERT( my_reserved && my_has_cached_item, "releasing non-existent reservation" );
my_reserved = false;
if(!my_successors.empty())
spawn_put();
return true;
}
//! Consumes a reserved item
bool try_consume( ) override {
spin_mutex::scoped_lock lock(my_mutex);
__TBB_ASSERT( my_reserved && my_has_cached_item, "consuming non-existent reservation" );
my_reserved = false;
my_has_cached_item = false;
if ( !my_successors.empty() ) {
spawn_put();
}
return true;
}
//! Activates a node that was created in the inactive state
void activate() {
spin_mutex::scoped_lock lock(my_mutex);
my_active = true;
if (!my_successors.empty())
spawn_put();
}
template<typename Body>
Body copy_function_object() {
input_body<output_type> &body_ref = *this->my_body;
return dynamic_cast< input_body_leaf<output_type, Body> & >(body_ref).get_body();
}
protected:
//! resets the input_node to its initial state
void reset_node( reset_flags f) override {
my_active = false;
my_reserved = false;
my_has_cached_item = false;
if(f & rf_clear_edges) my_successors.clear();
if(f & rf_reset_bodies) {
input_body<output_type> *tmp = my_init_body->clone();
delete my_body;
my_body = tmp;
}
}
private:
spin_mutex my_mutex;
bool my_active;
input_body<output_type> *my_body;
input_body<output_type> *my_init_body;
broadcast_cache< output_type > my_successors;
bool my_reserved;
bool my_has_cached_item;
output_type my_cached_item;
// used by apply_body_bypass, can invoke body of node.
bool try_reserve_apply_body(output_type &v) {
spin_mutex::scoped_lock lock(my_mutex);
if ( my_reserved ) {
return false;
}
if ( !my_has_cached_item ) {
d1::flow_control control;
fgt_begin_body( my_body );
my_cached_item = (*my_body)(control);
my_has_cached_item = !control.is_pipeline_stopped;
fgt_end_body( my_body );
}
if ( my_has_cached_item ) {
v = my_cached_item;
my_reserved = true;
return true;
} else {
return false;
}
}
graph_task* create_put_task() {
d1::small_object_allocator allocator{};
typedef input_node_task_bypass< input_node<output_type> > task_type;
graph_task* t = allocator.new_object<task_type>(my_graph, allocator, *this);
return t;
}
//! Spawns a task that applies the body
void spawn_put( ) {
if(is_graph_active(this->my_graph)) {
spawn_in_graph_arena(this->my_graph, *create_put_task());
}
}
friend class input_node_task_bypass< input_node<output_type> >;
//! Applies the body. Returning SUCCESSFULLY_ENQUEUED okay; forward_task_bypass will handle it.
graph_task* apply_body_bypass( ) {
output_type v;
if ( !try_reserve_apply_body(v) )
return nullptr;
graph_task *last_task = my_successors.try_put_task(v);
if ( last_task )
try_consume();
else
try_release();
return last_task;
}
}; // class input_node
//! Implements a function node that supports Input -> Output
template<typename Input, typename Output = continue_msg, typename Policy = queueing>
__TBB_requires(std::default_initializable<Input> &&
std::copy_constructible<Input> &&
std::copy_constructible<Output>)
class function_node
: public graph_node
, public function_input< Input, Output, Policy, cache_aligned_allocator<Input> >
, public function_output<Output>
{
typedef cache_aligned_allocator<Input> internals_allocator;
public:
typedef Input input_type;
typedef Output output_type;
typedef function_input<input_type,output_type,Policy,internals_allocator> input_impl_type;
typedef function_input_queue<input_type, internals_allocator> input_queue_type;
typedef function_output<output_type> fOutput_type;
typedef typename input_impl_type::predecessor_type predecessor_type;
typedef typename fOutput_type::successor_type successor_type;
using input_impl_type::my_predecessors;
//! Constructor
// input_queue_type is allocated here, but destroyed in the function_input_base.
// TODO: pass the graph_buffer_policy to the function_input_base so it can all
// be done in one place. This would be an interface-breaking change.
template< typename Body >
__TBB_requires(function_node_body<Body, Input, Output>)
__TBB_NOINLINE_SYM function_node( graph &g, size_t concurrency,
Body body, Policy = Policy(), node_priority_t a_priority = no_priority )
: graph_node(g), input_impl_type(g, concurrency, body, a_priority),
fOutput_type(g) {
fgt_node_with_body( CODEPTR(), FLOW_FUNCTION_NODE, &this->my_graph,
static_cast<receiver<input_type> *>(this), static_cast<sender<output_type> *>(this), this->my_body );
}
template <typename Body>
__TBB_requires(function_node_body<Body, Input, Output>)
function_node( graph& g, size_t concurrency, Body body, node_priority_t a_priority )
: function_node(g, concurrency, body, Policy(), a_priority) {}
#if __TBB_PREVIEW_FLOW_GRAPH_NODE_SET
template <typename Body, typename... Args>
__TBB_requires(function_node_body<Body, Input, Output>)
function_node( const node_set<Args...>& nodes, size_t concurrency, Body body,
Policy p = Policy(), node_priority_t a_priority = no_priority )
: function_node(nodes.graph_reference(), concurrency, body, p, a_priority) {
make_edges_in_order(nodes, *this);
}
template <typename Body, typename... Args>
__TBB_requires(function_node_body<Body, Input, Output>)
function_node( const node_set<Args...>& nodes, size_t concurrency, Body body, node_priority_t a_priority )
: function_node(nodes, concurrency, body, Policy(), a_priority) {}
#endif // __TBB_PREVIEW_FLOW_GRAPH_NODE_SET
//! Copy constructor
__TBB_NOINLINE_SYM function_node( const function_node& src ) :
graph_node(src.my_graph),
input_impl_type(src),
fOutput_type(src.my_graph) {
fgt_node_with_body( CODEPTR(), FLOW_FUNCTION_NODE, &this->my_graph,
static_cast<receiver<input_type> *>(this), static_cast<sender<output_type> *>(this), this->my_body );
}
protected:
template< typename R, typename B > friend class run_and_put_task;
template<typename X, typename Y> friend class broadcast_cache;
template<typename X, typename Y> friend class round_robin_cache;
using input_impl_type::try_put_task;
broadcast_cache<output_type> &successors () override { return fOutput_type::my_successors; }
void reset_node(reset_flags f) override {
input_impl_type::reset_function_input(f);
// TODO: use clear() instead.
if(f & rf_clear_edges) {
successors().clear();
my_predecessors.clear();
}
__TBB_ASSERT(!(f & rf_clear_edges) || successors().empty(), "function_node successors not empty");
__TBB_ASSERT(this->my_predecessors.empty(), "function_node predecessors not empty");
}
}; // class function_node
//! implements a function node that supports Input -> (set of outputs)
// Output is a tuple of output types.
template<typename Input, typename Output, typename Policy = queueing>
__TBB_requires(std::default_initializable<Input> &&
std::copy_constructible<Input>)
class multifunction_node :
public graph_node,
public multifunction_input
<
Input,
typename wrap_tuple_elements<
std::tuple_size<Output>::value, // #elements in tuple
multifunction_output, // wrap this around each element
Output // the tuple providing the types
>::type,
Policy,
cache_aligned_allocator<Input>
>
{
typedef cache_aligned_allocator<Input> internals_allocator;
protected:
static const int N = std::tuple_size<Output>::value;
public:
typedef Input input_type;
typedef null_type output_type;
typedef typename wrap_tuple_elements<N,multifunction_output, Output>::type output_ports_type;
typedef multifunction_input<
input_type, output_ports_type, Policy, internals_allocator> input_impl_type;
typedef function_input_queue<input_type, internals_allocator> input_queue_type;
private:
using input_impl_type::my_predecessors;
public:
template<typename Body>
__TBB_requires(multifunction_node_body<Body, Input, output_ports_type>)
__TBB_NOINLINE_SYM multifunction_node(
graph &g, size_t concurrency,
Body body, Policy = Policy(), node_priority_t a_priority = no_priority
) : graph_node(g), input_impl_type(g, concurrency, body, a_priority) {
fgt_multioutput_node_with_body<N>(
CODEPTR(), FLOW_MULTIFUNCTION_NODE,
&this->my_graph, static_cast<receiver<input_type> *>(this),