ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
Mailbox.h
Go to the documentation of this file.
1/*--------------------------------------------------------------------------*/
2/*----------------------------- File Mailbox.h -----------------------------*/
3/*--------------------------------------------------------------------------*/
135/*--------------------------------------------------------------------------*/
136/*----------------------------- DEFINITIONS --------------------------------*/
137/*--------------------------------------------------------------------------*/
138
139#ifndef __ADS_Mailbox
140 #define __ADS_Mailbox
141/* self-identification: #endif constant */
142
143/*--------------------------------------------------------------------------*/
144/*------------------------------ INCLUDES ----------------------------------*/
145/*--------------------------------------------------------------------------*/
146
147#include "ADS/Contract.h"
148#include "ADS/Portable.h"
150
151#include <atomic>
152#include <concepts>
153#include <cstddef>
154#include <cstdint>
155#include <functional>
156#include <memory>
157#include <span>
158#include <type_traits>
159#include <unordered_map>
160#include <utility>
161#include <vector>
162
163/*--------------------------------------------------------------------------*/
164/*--------------------------- NAMESPACE ------------------------------------*/
165/*--------------------------------------------------------------------------*/
166
167namespace ADS
168{
169
173template< class K , class H = std::hash< K > >
174[[nodiscard]] std::size_t ownerOf( const K & k , std::size_t p ,
175 const H & h = H() )
176{
177 ADS_PRE( p >= 1 );
178 return( std::size_t( h( k ) ) % p );
179 }
180
181/*--------------------------------------------------------------------------*/
182/*--------------------- THE POLICIES OF THE COALESCING ---------------------*/
183/*--------------------------------------------------------------------------*/
184
188{ };
189
196template< class K , class M = void >
198{
199 using KeyOf = K;
200 using Map = M;
201 };
202
203namespace detail
204{
205
207template< class C >
208struct CoalescePolicy
209{
210 static constexpr bool on = false;
211 };
212
214template< class K , class M >
215struct CoalescePolicy< CoalesceBy< K , M > >
216{
217 static constexpr bool on = true;
218 using KeyOf = K;
219 };
220
222template< class C , class Msg >
223struct Coalescing
224{
225 static constexpr bool on = false;
226 struct Slots
227 { };
228 };
229
232template< class K , class M , class Msg >
233struct Coalescing< CoalesceBy< K , M > , Msg >
234{
235 static constexpr bool on = true;
236 using KeyOf = K;
237 using Key =
238 std::remove_cvref_t< std::invoke_result_t< const K & , const Msg & > >;
239 using Map = std::conditional_t< std::is_void_v< M > ,
240 std::unordered_map< Key , std::size_t > , M >;
241 using Slots = std::vector< Map >;
242 };
243
247template< class I >
248[[nodiscard]] constexpr auto & mappedOf( const I & it )
249{
250 if constexpr( std::is_pointer_v< I > )
251 return( *it );
252 else
253 return( it->second );
254 }
255
256} // end( namespace detail )
257
262template< class C , class Msg >
264 std::same_as< C , NoCoalescing > ||
265 ( detail::CoalescePolicy< C >::on &&
266 std::default_initializable<
267 typename detail::CoalescePolicy< C >::KeyOf > &&
268 std::invocable< const typename detail::CoalescePolicy< C >::KeyOf & ,
269 const Msg & > &&
270 requires( typename detail::Coalescing< C , Msg >::Map & m ,
271 const typename detail::Coalescing< C , Msg >::Key & k ,
272 std::size_t i )
273{
274 {
275 detail::mappedOf( m.try_emplace( k , i ).first )
276 } -> std::same_as< std::size_t & >;
277 { m.try_emplace( k , i ).second } -> std::convertible_to< bool >;
278 m.clear();
279 { m.empty() } -> std::convertible_to< bool >;
280 } );
281
282/*--------------------------------------------------------------------------*/
283/*----------------------------- CLASS Mailbox ------------------------------*/
284/*--------------------------------------------------------------------------*/
285
291template< class Msg , ChannelFamily Ch = MeshChannels< Msg > ,
292 class Co = NoCoalescing >
294{
295
296 static_assert( MailboxCoalescing< Co , Msg > ,
297 "the policy of the coalescing is NoCoalescing or a "
298 "CoalesceBy with a key and a map" );
299
301 using Coalesce = detail::Coalescing< Co , Msg >;
302
304 static constexpr bool coalescing = Coalesce::on;
305
307 template< class F >
308 static constexpr bool merges = std::invocable< F & , Msg & , const Msg & >;
309
310/*--------------------------------------------------------------------------*/
311 public:
312 using Message = Msg;
313 using Channels = Ch;
314 using Coalescing = Co;
315
319 template< class... A >
320 explicit Mailbox( std::size_t p , std::size_t batch = 64 , A &&... args )
321 : f_ch( p , std::forward< A >( args )... ) , f_worker( p ) ,
322 f_batch( batch ) {
323 ADS_PRE( ( p >= 1 ) && ( batch >= 1 ) );
324 for( auto & w : f_worker ) {
325 w = std::make_unique< Worker >();
326 w->out.resize( p );
327 w->next.assign( p , batch );
328 w->listed.assign( p , 0 );
329 if constexpr( coalescing )
330 w->slots.resize( p );
331 }
332 f_count.value.store( std::int64_t( p ) , std::memory_order_relaxed );
333 }
334
336 [[nodiscard]] std::size_t size( void ) const { return( f_worker.size() ); }
337
360 void send( std::size_t me , std::size_t to , Msg x ) {
361 ADS_PRE( ( me < size() ) && ( to < size() ) );
362 Worker & w = *f_worker[ me ];
363 ADS_PRE( w.active || stopped() );
364 auto & o = w.out[ to ];
365 if( ! w.listed[ to ] ) {
366 w.listed[ to ] = 1;
367 w.dirty.push_back( to );
368 }
369 o.push_back( std::move( x ) );
370 if constexpr( coalescing ) // no merge into a place before x
371 detail::mappedOf(
372 w.slots[ to ]
373 .try_emplace( typename Coalesce::KeyOf()( o.back() ) , kClosed )
374 .first ) = kClosed;
375 if( ( o.size() >= w.next[ to ] ) && ! stopped() )
376 push( me , to );
377 }
378
410 template< class F >
411 requires( coalescing && merges< F > )
412 void send( std::size_t me , std::size_t to , Msg x , F && merge ) {
413 ADS_PRE( ( me < size() ) && ( to < size() ) );
414 Worker & w = *f_worker[ me ];
415 ADS_PRE( w.active || stopped() );
416 auto & o = w.out[ to ];
417 if( ! w.listed[ to ] ) {
418 w.listed[ to ] = 1;
419 w.dirty.push_back( to );
420 }
421 o.push_back( std::move( x ) );
422 const std::size_t i = o.size() - 1;
423 auto [ it , fresh ] =
424 w.slots[ to ].try_emplace( typename Coalesce::KeyOf()( o.back() ) , i );
425 if( ! fresh ) {
426 const std::size_t j = detail::mappedOf( it );
427 ADS_INVARIANT( ( j < i ) || ( j == kClosed ) );
428 if( ( j != kClosed ) && absorb( merge , o[ j ] , o.back() ) ) {
429 o.pop_back(); // never counted, never pushed
430 ++w.merged;
431 return;
432 }
433 detail::mappedOf( it ) = i;
434 }
435 if( ( o.size() >= w.next[ to ] ) && ! stopped() )
436 push( me , to );
437 }
438
464 bool flush( std::size_t me ) {
465 ADS_PRE( me < size() );
466 Worker & w = *f_worker[ me ];
467 const bool go = ! stopped();
468 std::size_t keep = 0;
469 for( std::size_t i = 0 ; i < w.dirty.size() ; ++i ) {
470 const std::size_t to = w.dirty[ i ];
471 if( go )
472 push( me , to );
473 if( w.out[ to ].empty() )
474 w.listed[ to ] = 0;
475 else
476 w.dirty[ keep++ ] = to;
477 }
478 w.dirty.resize( keep );
479 return( keep == 0 );
480 }
481
500 template< class F >
501 std::size_t poll( std::size_t me , F && f ) {
502 ADS_PRE( me < size() );
503 if( stopped() )
504 return( 0 );
505 Worker & w = *f_worker[ me ];
506 const std::size_t k = f_ch.drain( me , [ & ]( Msg && x ) {
507 if( ! w.active ) { // back to work, counted
508 f_count.value.fetch_add( 1 , std::memory_order_acq_rel );
509 w.active = true;
510 }
511 f( std::move( x ) );
512 } );
513 if( k > 0 ) {
514 w.received += k;
515 f_count.value.fetch_sub( std::int64_t( k ) , std::memory_order_acq_rel );
516 }
517 return( k );
518 }
519
539 bool quiescent( std::size_t me ) {
540 ADS_PRE( me < size() );
541 if( stopped() )
542 return( true );
543 Worker & w = *f_worker[ me ];
544 if( w.active ) {
545 if( ! flush( me ) )
546 return( false );
547 w.active = false;
548 if( f_count.value.fetch_sub( 1 , std::memory_order_acq_rel ) == 1 )
549 return( true );
550 }
551 return( f_count.value.load( std::memory_order_acquire ) == 0 );
552 }
553
556 [[nodiscard]] bool terminated( void ) const {
557 return( stopped() ||
558 ( f_count.value.load( std::memory_order_acquire ) == 0 ) );
559 }
560
567 void stop( void ) { f_stop.value.store( true , std::memory_order_release ); }
568
570 [[nodiscard]] bool stopped( void ) const {
571 return( f_stop.value.load( std::memory_order_acquire ) );
572 }
573
594 template< class F >
595 requires std::predicate< F & , std::size_t >
596 void rearm( F && active ) {
597 ADS_PRE( rearmable() );
598 ADS_AUDIT( drained() );
599 std::int64_t n = 0;
600 for( std::size_t me = 0 ; me < size() ; ++me ) {
601 Worker & w = *f_worker[ me ];
602 w.active = bool( active( me ) );
603 n += w.active;
604 }
605 f_count.value.store( n , std::memory_order_release );
606 f_stop.value.store( false , std::memory_order_release );
607 }
608
611 void rearm( void ) {
612 rearm( []( std::size_t ) { return( true ); } );
613 }
614
633 template< class P >
634 requires( std::predicate< P & , std::size_t > || std::predicate< P & > )
635 void audit( [[maybe_unused]] P && pred ) {
636 if constexpr( ADS_CONTRACTS >= 3 ) {
637 ADS_AUDIT( rearmable() );
638 ADS_AUDIT( drained() );
639 if constexpr( std::predicate< P & , std::size_t > ) {
640 for( std::size_t me = 0 ; me < size() ; ++me )
641 ADS_AUDIT( pred( me ) );
642 }
643 else
644 ADS_AUDIT( pred() );
645 }
646 }
647
668 template< class F >
669 std::size_t leftovers( std::size_t me , F && f ) {
670 ADS_PRE( me < size() );
671 Worker & w = *f_worker[ me ];
672 std::size_t n = 0;
673 for( const std::size_t to : w.dirty ) {
674 auto & o = w.out[ to ];
675 n += o.size();
676 for( auto & x : o )
677 f( std::move( x ) );
678 o.clear();
679 if constexpr( coalescing )
680 w.slots[ to ].clear();
681 w.listed[ to ] = 0;
682 w.next[ to ] = f_batch;
683 }
684 w.dirty.clear();
685 return( n + f_ch.drain( me , [ & ]( Msg && x ) { f( std::move( x ) ); } ) );
686 }
687
691 template< class F >
692 std::size_t leftovers( F && f ) {
693 std::size_t n = 0;
694 for( std::size_t me = 0 ; me < size() ; ++me )
695 n += leftovers( me , f );
696 return( n );
697 }
698
700 [[nodiscard]] std::uint64_t sent( std::size_t me ) const {
701 ADS_PRE( me < size() );
702 return( f_worker[ me ]->sent );
703 }
704
707 [[nodiscard]] std::uint64_t batches( std::size_t me ) const {
708 ADS_PRE( me < size() );
709 return( f_worker[ me ]->batches );
710 }
711
714 [[nodiscard]] std::uint64_t merged( std::size_t me ) const {
715 ADS_PRE( me < size() );
716 return( f_worker[ me ]->merged );
717 }
718
720 [[nodiscard]] std::uint64_t received( std::size_t me ) const {
721 ADS_PRE( me < size() );
722 return( f_worker[ me ]->received );
723 }
724
726 [[nodiscard]] Ch & channels( void ) { return( f_ch ); }
727
728/*--------------------------------------------------------------------------*/
729 private:
731 static constexpr std::size_t kClosed = std::size_t( -1 );
732
734 struct alignas( 128 ) Worker
735 {
736 std::vector< std::vector< Msg > > out;
737 std::vector< std::size_t > next;
738 std::vector< char > listed;
739 std::vector< std::size_t > dirty;
740 bool active = true;
741 std::uint64_t sent = 0;
742 std::uint64_t batches = 0;
743 std::uint64_t received = 0;
744 std::uint64_t merged = 0;
747 ADS_NO_UNIQUE_ADDRESS typename Coalesce::Slots slots{};
748 };
749
751 struct alignas( 128 ) Counter
752 {
753 std::atomic< std::int64_t > value{ 0 };
754 };
755
757 struct alignas( 128 ) Flag
758 {
759 std::atomic< bool > value{ false };
760 };
761
764 [[nodiscard]] bool rearmable( void ) const {
765 for( const auto & w : f_worker )
766 for( const std::size_t to : w->dirty )
767 if( ! w->out[ to ].empty() )
768 return( false );
769 return( stopped() ||
770 ( f_count.value.load( std::memory_order_acquire ) == 0 ) );
771 }
772
775 [[nodiscard]] bool drained( void ) {
776 std::size_t n = 0;
777 for( std::size_t me = 0 ; me < size() ; ++me )
778 n += f_ch.drain( me , []( Msg && ) { } );
779 return( n == 0 );
780 }
781
784 template< class F >
785 static bool absorb( F & merge , Msg & p , const Msg & x ) {
786 if constexpr( std::is_void_v<
787 std::invoke_result_t< F & , Msg & , const Msg & > > ) {
788 merge( p , x );
789 return( true );
790 }
791 else
792 return( bool( merge( p , x ) ) );
793 }
794
797 void push( std::size_t me , std::size_t to ) {
798 Worker & w = *f_worker[ me ];
799 auto & o = w.out[ to ];
800 const std::size_t k = o.size();
801 if( k == 0 )
802 return;
803 f_count.value.fetch_add( std::int64_t( k ) , std::memory_order_acq_rel );
804 const std::size_t j = f_ch.tryPush( me , to , std::span< const Msg >( o ) );
805 if( j < k )
806 f_count.value.fetch_sub( std::int64_t( k - j ) ,
807 std::memory_order_acq_rel );
808 if( j > 0 ) {
809 w.sent += j;
810 ++w.batches;
811 o.erase( o.begin() , o.begin() + std::ptrdiff_t( j ) );
812 if constexpr( coalescing ) // the places have shifted
813 if( ! w.slots[ to ].empty() )
814 w.slots[ to ].clear();
815 }
816 w.next[ to ] = o.size() + f_batch;
817 }
818
819 Ch f_ch;
820 std::vector< std::unique_ptr< Worker > > f_worker;
821 std::size_t f_batch;
822 Counter f_count;
823 Flag f_stop;
824 }; // end( class Mailbox )
825
826/*--------------------------------------------------------------------------*/
827
828} // end( namespace ADS )
829
830/*--------------------------------------------------------------------------*/
831
832#endif /* Mailbox.h included */
833
834/*--------------------------------------------------------------------------*/
835/*-------------------------- End File Mailbox.h ----------------------------*/
836/*--------------------------------------------------------------------------*/
The channels between the long-lived workers of an executor [see Executor.h], beyond the book: worker...
The contracts of ADS: the preconditions, the postconditions and the invariants of the operations,...
The primitives of the processor that the compilers spell each in their own way, in one form for all: ...
std::size_t poll(std::size_t me, F &&f)
the calls f( x ) on the messages of the inbox of me, and their number; a passive worker that finds me...
Definition Mailbox.h:501
Co Coalescing
< the family of the channels
Definition Mailbox.h:314
std::uint64_t sent(std::size_t me) const
the messages that me has pushed so far
Definition Mailbox.h:700
bool terminated(void) const
true once the computation has ended or the mailbox has stopped (any thread may ask)
Definition Mailbox.h:556
Ch & channels(void)
the channels underneath
Definition Mailbox.h:726
void rearm(void)
rearm() above with all the workers active, as at the construction
Definition Mailbox.h:611
std::size_t size(void) const
the number of the workers
Definition Mailbox.h:336
Mailbox(std::size_t p, std::size_t batch=64, A &&... args)
< the policy of the coalescing
Definition Mailbox.h:320
std::uint64_t batches(std::size_t me) const
the batches that me has pushed so far, i.e., the pushes that the channels took at least one message o...
Definition Mailbox.h:707
void audit(P &&pred)
at the level of the audits, the predicate of the consumer checked at a quiescent point: pred( me ) fo...
Definition Mailbox.h:635
std::uint64_t received(std::size_t me) const
the messages that me has drained so far by poll()
Definition Mailbox.h:720
std::uint64_t merged(std::size_t me) const
the messages that me has merged so far into one pending, by send() with a merge; 0 with NoCoalescing
Definition Mailbox.h:714
Msg Message
Definition Mailbox.h:312
bool stopped(void) const
true once stop() has been called
Definition Mailbox.h:570
bool quiescent(std::size_t me)
true if the computation has ended or the mailbox has stopped; called by me with no work left,...
Definition Mailbox.h:539
void send(std::size_t me, std::size_t to, Msg x, F &&merge)
send( me , to , x ) with the coalescing of the policy: merged into the last message of its key in th...
Definition Mailbox.h:412
void send(std::size_t me, std::size_t to, Msg x)
appended to the outbox of me for to, which is pushed when it holds a batch more than a push left in i...
Definition Mailbox.h:360
void stop(void)
ends the computation at once, whatever the messages on their way: from then on quiescent() and termin...
Definition Mailbox.h:567
std::size_t leftovers(std::size_t me, F &&f)
the calls f( x ) on the messages left to me: those of its outboxes, for each destination in the order...
Definition Mailbox.h:669
bool flush(std::size_t me)
the outboxes of me pushed, true if all of them are empty after it: a bounded family may refuse some m...
Definition Mailbox.h:464
void rearm(F &&active)
the mailbox ready for the next computation, with the workers for which active( me ) is true active an...
Definition Mailbox.h:596
std::size_t leftovers(F &&f)
leftovers( me , f ) of every worker, in the order of the workers, and the number of all the messages
Definition Mailbox.h:692
Ch Channels
< the type of the messages
Definition Mailbox.h:313
a policy of the coalescing of Mailbox for the messages Msg: NoCoalescing, or CoalesceBy< K ,...
Definition Mailbox.h:263
#define ADS_PRE(cond)
[check]
Definition Contract.h:121
#define ADS_INVARIANT(cond)
an invariant, checked from level 3
Definition Contract.h:127
#define ADS_AUDIT(cond)
a precondition or a postcondition dearer than the operation, checked from level 3
Definition Contract.h:131
#define ADS_CONTRACTS
the level of the contracts checked: 0 none, 1 preconditions, 2 postconditions, 3 invariants and audit...
Definition Contract.h:71
Batch< S > batch(S &s)
a batch on the structure , open while it lives: its events are collected, and the outermost batch sen...
Definition Modification.h:2150
#define ADS_NO_UNIQUE_ADDRESS
an empty member that takes no storage, by the attribute that does so (the standard one is accepted bu...
Definition Portable.h:81
std::size_t ownerOf(const K &k, std::size_t p, const H &h=H())
the owner of the key among workers or processes, for the hash function
Definition Mailbox.h:174
SortedListSet< T > merge(const SortedListSet< T > &A, const SortedListSet< T > &B, bool a, bool b, bool both)
the merge of the sorted lists of and : an item of only, of only or of both goes into the result if...
Definition ADT.h:96
the coalescing of the messages of one key in an outbox of Mailbox: K()( x ) the key of the message ,...
Definition Mailbox.h:198
M Map
< the function of the key
Definition Mailbox.h:200
K KeyOf
Definition Mailbox.h:199
no coalescing of the messages in the outboxes of Mailbox: no member and no code, and no send() with a...
Definition Mailbox.h:188