ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
StealablePriorityQueue.h
Go to the documentation of this file.
1/*--------------------------------------------------------------------------*/
2/*---------------------- File StealablePriorityQueue.h ---------------------*/
3/*--------------------------------------------------------------------------*/
129/*--------------------------------------------------------------------------*/
130/*----------------------------- DEFINITIONS --------------------------------*/
131/*--------------------------------------------------------------------------*/
132
133#ifndef __ADS_StealablePriorityQueue
134 #define __ADS_StealablePriorityQueue
135/* self-identification: #endif constant */
136
137/*--------------------------------------------------------------------------*/
138/*------------------------------ INCLUDES ----------------------------------*/
139/*--------------------------------------------------------------------------*/
140
141#include "ADS/Contract.h"
142#include "ADS/Portable.h"
146
147#include <atomic>
148#include <cstddef>
149#include <cstdint>
150#include <exception>
151#include <functional>
152#include <iterator>
153#include <memory>
154#include <new>
155#include <optional>
156#include <type_traits>
157#include <utility>
158#include <vector>
159
162#define ADS_SPQ_INLINE ADS_ALWAYS_INLINE
163
165#define ADS_SPQ_NOINLINE ADS_NOINLINE
166
167/*--------------------------------------------------------------------------*/
168/*--------------------------- NAMESPACE ------------------------------------*/
169/*--------------------------------------------------------------------------*/
170
171namespace ADS
172{
173
174namespace detail
175{
176
178struct SpqNoBound
179{ };
180
183template< class K , class T , class Bd >
184struct SpqEntry
185{
186 K key;
187 Bd bound;
188 T item;
189 };
190
192template< class K , class T >
193struct SpqEntry< K , T , void >
194{
195 K key;
196 T item;
197 };
198
214template< class E , class By , class Bd , class BdLess >
215class SpqHalf
216{
217
218 static_assert( std::is_nothrow_copy_constructible_v< Bd > &&
219 std::is_nothrow_move_constructible_v< E > &&
220 std::is_nothrow_move_assignable_v< E > ,
221 "the moves of the pairs and the copies of the bounds do not "
222 "throw" );
223
224 public:
226 static constexpr bool bounded = true;
227
229 SpqHalf( By by , BdLess bl ) : f_by( by ) , f_bl( bl ) { }
230
235 void push( const E & e ) {
236 std::size_t i = f_E.size();
237 f_E.push_back( e ); // the only throws, no change
238 if( f_sub )
239 try {
240 f_M.push_back( e.bound );
241 }
242 catch( ... ) {
243 f_E.pop_back();
244 throw;
245 }
246 const std::size_t leaf = i;
247 if( i > 0 ) {
248 E x = std::move( f_E[ i ] );
249 while( i > 0 ) {
250 const std::size_t p = ( i - 1 ) / 4;
251 if( ! f_by( x , f_E[ p ] ) )
252 break;
253 f_E[ i ] = std::move( f_E[ p ] );
254 i = p;
255 }
256 f_E[ i ] = std::move( x );
257 }
258 if( f_sub ) {
259 for( std::size_t j = leaf ; j != i ; j = ( j - 1 ) / 4 )
260 fix( j ); // the nodes the hole passed
261 const Bd b = e.bound; // the leaf has it already
262 for( std::size_t j = i ; ; j = ( j - 1 ) / 4 ) {
263 if( j != leaf ) {
264 if( ! f_bl( b , f_M[ j ] ) )
265 break; // and so all those above
266 f_M[ j ] = b;
267 }
268 if( j == 0 )
269 break;
270 }
271 }
272 else if( f_known && f_bl( e.bound , f_least ) )
273 f_least = e.bound;
274 }
275
280 E pop( void ) {
281 E r = std::move( f_E.front() );
282 E z = std::move( f_E.back() );
283 const Bd bz = z.bound;
284 f_E.pop_back();
285 if( f_sub )
286 f_M.pop_back();
287 const std::size_t n = f_E.size();
288 ++f_pops;
289 if( f_known && ! f_bl( f_least , r.bound ) )
290 f_known = false; // the least bound may be gone
291 if( n == 0 )
292 return( r );
293 std::size_t i = 0;
294 for( ; ; ) {
295 const std::size_t c = 4 * i + 1;
296 if( c >= n )
297 break;
298 std::size_t b = c;
299 const std::size_t last = c + 4 < n ? c + 4 : n;
300 for( std::size_t k = c + 1 ; k < last ; ++k )
301 if( f_by( f_E[ k ] , f_E[ b ] ) )
302 b = k;
303 if( ! f_by( f_E[ b ] , z ) )
304 break;
305 f_E[ i ] = std::move( f_E[ b ] );
306 i = b;
307 }
308 f_E[ i ] = std::move( z );
309 if( f_sub ) {
310 // the path of the old last leaf first: a node off the path down lost z
311 // alone, and keeps its least bound, as all those above it off the path
312 // down, if that bound is less than the one of z; the nodes of the path
313 // down, all fixed after, read the children fixed here
314 for( std::size_t j = n ; j > 0 ; ) {
315 j = ( j - 1 ) / 4;
316 if( f_bl( f_M[ j ] , bz ) )
317 break;
318 fix( j );
319 }
320 for( std::size_t j = i ; ; j = ( j - 1 ) / 4 ) { // the path down
321 fix( j );
322 if( j == 0 )
323 break;
324 }
325 }
326 return( r );
327 }
328
330 [[nodiscard]] const E & top( void ) const { return( f_E.front() ); }
331
336 [[nodiscard]] Bd minBound( void ) const {
337 if( f_sub )
338 return( f_M.front() );
339 if( f_known )
340 return( f_least );
341 return( rescan() );
342 }
343
345 [[nodiscard]] bool subtrees( void ) const { return( f_sub ); }
346
348 [[nodiscard]] std::size_t size( void ) const { return( f_E.size() ); }
350 [[nodiscard]] bool empty( void ) const { return( f_E.empty() ); }
352 [[nodiscard]] const E * begin( void ) const { return( f_E.data() ); }
354 [[nodiscard]] const E * end( void ) const {
355 return( f_E.data() + f_E.size() );
356 }
357
359 void clear( void ) {
360 f_E.clear();
361 f_M.clear();
362 f_known = false;
363 }
364
369 template< std::forward_iterator I , std::sentinel_for< I > S >
370 void assign( I first , S last ) {
371 std::vector< E , HugePageAllocator< E > > A( first , last );
372 std::vector< Bd , HugePageAllocator< Bd > > M( f_sub ? A.size() : 0 );
373 f_E.swap( A ); // nothing thrown from here on
374 f_M.swap( M );
375 f_known = false;
376 const std::size_t n = f_E.size();
377 if( n > 1 )
378 for( std::size_t i = ( n - 2 ) / 4 + 1 ; i-- > 0 ; ) {
379 E x = std::move( f_E[ i ] );
380 std::size_t h = i;
381 for( ; ; ) {
382 const std::size_t c = 4 * h + 1;
383 if( c >= n )
384 break;
385 std::size_t b = c;
386 const std::size_t end = c + 4 < n ? c + 4 : n;
387 for( std::size_t k = c + 1 ; k < end ; ++k )
388 if( f_by( f_E[ k ] , f_E[ b ] ) )
389 b = k;
390 if( ! f_by( f_E[ b ] , x ) )
391 break;
392 f_E[ h ] = std::move( f_E[ b ] );
393 h = b;
394 }
395 f_E[ h ] = std::move( x );
396 }
397 if( f_sub )
398 for( std::size_t i = n ; i-- > 0 ; )
399 fix( i );
400 }
401
405 [[nodiscard]] bool consistent( void ) const {
406 const std::size_t n = f_E.size();
407 for( std::size_t i = 1 ; i < n ; ++i )
408 if( f_by( f_E[ i ] , f_E[ ( i - 1 ) / 4 ] ) )
409 return( false );
410 if( f_sub ) {
411 if( f_M.size() != n )
412 return( false );
413 for( std::size_t i = 0 ; i < n ; ++i ) {
414 Bd m = f_E[ i ].bound;
415 for( std::size_t c = 4 * i + 1 ; ( c < n ) && ( c <= 4 * i + 4 ) ; ++c )
416 if( f_bl( f_M[ c ] , m ) )
417 m = f_M[ c ];
418 if( f_bl( m , f_M[ i ] ) || f_bl( f_M[ i ] , m ) )
419 return( false );
420 }
421 }
422 else if( f_known && ( n > 0 ) ) {
423 Bd m = f_E.front().bound;
424 for( const E & e : f_E )
425 if( f_bl( e.bound , m ) )
426 m = e.bound;
427 if( f_bl( m , f_least ) || f_bl( f_least , m ) )
428 return( false );
429 }
430 return( true );
431 }
432
433 private:
436 ADS_SPQ_NOINLINE Bd rescan( void ) const {
437 const std::size_t n = f_E.size();
438 Bd m = f_E.front().bound;
439 for( std::size_t k = 1 ; k < n ; ++k ) {
440 const Bd x = f_E[ k ].bound;
441 m = f_bl( x , m ) ? x : m;
442 }
443 f_least = m;
444 f_known = true;
445 f_scanned += n;
446 if( ( n >= 64 ) && ( f_scanned > 16 * ( f_pops + n ) + 65536 ) )
447 try { // to the least bounds of the
448 f_M.resize( n ); // subtrees, if there is room
449 for( std::size_t k = n ; k-- > 0 ; )
450 fix( k );
451 f_sub = true;
452 }
453 catch( const std::bad_alloc & ) { // the scans go on
454 f_M.clear();
455 }
456 return( m );
457 }
458
461 void fix( std::size_t j ) const {
462 const std::size_t n = f_E.size();
463 Bd m = f_E[ j ].bound;
464 const std::size_t c = 4 * j + 1;
465 const std::size_t last = c + 4 < n ? c + 4 : n;
466 // one load per child, in a chain of selects: a vector load of the four
467 // would wait for the stores of their bounds, just written, which cannot
468 // be forwarded to a wider load
469 const Bd * M = f_M.data();
470 for( std::size_t k = c ; k < last ; ++k ) {
471 const Bd x = load( M[ k ] );
472 m = f_bl( x , m ) ? x : m;
473 }
474 f_M[ j ] = m;
475 }
476
481 static Bd load( const Bd & x ) {
482 if constexpr( std::is_scalar_v< Bd > )
483 return( static_cast< const volatile Bd & >( x ) );
484 else
485 return( x );
486 }
487
488 std::vector< E , HugePageAllocator< E > > f_E;
490 mutable std::vector< Bd , HugePageAllocator< Bd > > f_M;
491 By f_by;
492 BdLess f_bl;
493 mutable Bd f_least{};
494 mutable bool f_known = false;
495 mutable bool f_sub = false;
496 mutable std::size_t f_scanned = 0;
497 std::size_t f_pops = 0;
498 };
499
502template< class E , class By , class BdLess >
503class SpqHalf< E , By , void , BdLess > : public DaryHeap< E , By , 4 >
504{
505 public:
507 static constexpr bool bounded = false;
509 SpqHalf( By by , BdLess ) : DaryHeap< E , By , 4 >( by ) { }
511 [[nodiscard]] bool consistent( void ) const { return( true ); }
512 };
513
514} // end( namespace detail )
515
516/*--------------------------------------------------------------------------*/
517/*--------------------- CLASS StealablePriorityQueue -----------------------*/
518/*--------------------------------------------------------------------------*/
519
524template< class K , class T , class Less = std::less< K > , class Bd = void ,
525 class BdLess = std::less<> >
527{
528
529/*--------------------------------------------------------------------------*/
530 public:
531 using Key = K;
532 using Item = T;
533
535 static constexpr bool bounded = ! std::is_void_v< Bd >;
536
538 using Bound = std::conditional_t< bounded , Bd , detail::SpqNoBound >;
539
541 using Entry = detail::SpqEntry< K , T , Bd >;
542
545 explicit StealablePriorityQueue( Less less = Less() , BdLess bl = BdLess() );
546
551
554
569 void push( K k , T x )
570 requires( ! bounded )
571 {
572 place( Entry{ std::move( k ) , std::move( x ) } );
573 }
574
578 void push( K k , Bound b , T x )
579 requires bounded
580 {
581 place( Entry{ std::move( k ) , std::move( b ) , std::move( x ) } );
582 }
583
617 [[nodiscard]] std::optional< Bound > minBound( void ) const
618 requires bounded;
619
646 std::optional< Entry > pop( void );
647
650 const Entry & top( void );
651
681 void serve( void );
682
712 std::size_t steal( StealablePriorityQueue & v );
713
716 [[nodiscard]] std::size_t size( void ) const;
717
719 [[nodiscard]] bool empty( void ) const { return( size() == 0 ); }
720
724 [[nodiscard]] bool stealable( void ) const {
725 return( ( f_offer.load( std::memory_order_relaxed ) != nullptr ) ||
726 f_canGive.load( std::memory_order_relaxed ) );
727 }
728
730 [[nodiscard]] bool offering( void ) const;
731
733 [[nodiscard]] std::pair< std::size_t , std::size_t > halves( void ) const {
734 return( std::make_pair( f_h[ 0 ].size() , f_h[ 1 ].size() ) );
735 }
736
739 [[nodiscard]] bool consistent( void ) const;
740
745 template< class F >
746 std::size_t drain( F && f );
747
748/*--------------------------------------------------------------------------*/
749 private:
751 struct ByKey
752 {
753 Less less;
755 bool operator()( const Entry & a , const Entry & b ) const {
756 return( less( a.key , b.key ) );
757 }
758 };
759
761 using Heap = detail::SpqHalf< Entry , ByKey , Bd , BdLess >;
762
764 void place( Entry && e );
765
767 [[nodiscard]] int best( void ) const;
768
770 void settle( void );
771
774 void merge( Heap & g );
775
777 void deal( void );
778
780 void hint( void );
781
783 void recount( void );
784
786 void answer( void );
787
791 [[nodiscard]] bool hinted( void ) const;
792
793 static constexpr std::size_t line = 64;
794
795 // of the owner alone
796 Heap f_h[ 2 ];
797 ByKey f_less;
798 BdLess f_bl;
799 std::optional< K > f_offerKey;
800 std::optional< Bound > f_offerBound;
801 std::size_t f_offerSize = 0;
802 std::size_t f_n[ 2 ] = { 0 , 0 };
803 bool f_offered = false;
804 bool f_can = false;
805 unsigned char f_turn = 1;
806
807 // shared with the thieves, on lines of their own (the alignment of the
808 // first rounds the size of the queue up to a multiple of two lines)
809 alignas( 2 * line ) std::atomic< Heap * > f_offer{ nullptr };
810 std::atomic< bool > f_hungry{ false };
811 std::atomic< bool > f_canGive{ false };
812
813 }; // end( class StealablePriorityQueue )
814
815/*--------------------------------------------------------------------------*/
816/*------------------------ CLASS StealingFrontier --------------------------*/
817/*--------------------------------------------------------------------------*/
818
823template< class K , class T , class Less = std::less< K > , class Bd = void ,
824 class BdLess = std::less<> >
826{
827
828/*--------------------------------------------------------------------------*/
829 public:
833 using Entry = typename Queue::Entry;
835 using Bound = typename Queue::Bound;
836
840 explicit StealingFrontier( std::size_t p , std::uint64_t seed = 1 ,
841 Less less = Less() , BdLess bl = BdLess() );
842
847
850
852 [[nodiscard]] std::size_t workers( void ) const { return( f_p ); }
853
856 [[nodiscard]] Queue & queue( std::size_t i ) {
857 ADS_PRE( i < workers() );
858 return( f_w[ i ].q );
859 }
860
863 void push( std::size_t i , K k , T x )
864 requires( ! Queue::bounded )
865 {
866 ADS_PRE( i < workers() );
867 f_w[ i ].q.push( std::move( k ) , std::move( x ) );
868 }
869
873 void push( std::size_t i , K k , Bound b , T x )
874 requires Queue::bounded
875 {
876 ADS_PRE( i < workers() );
877 f_w[ i ].q.push( std::move( k ) , std::move( b ) , std::move( x ) );
878 }
879
884 [[nodiscard]] std::optional< Bound > minBound( std::size_t i ) const
885 requires Queue::bounded
886 {
887 ADS_PRE( i < workers() );
888 return( f_w[ i ].q.minBound() );
889 }
890
896 template< class F >
897 std::size_t drain( std::size_t i , F && f ) {
898 ADS_PRE( i < workers() );
899 return( f_w[ i ].q.drain( std::forward< F >( f ) ) );
900 }
901
904 void serve( std::size_t i ) {
905 ADS_PRE( i < workers() );
906 f_w[ i ].q.serve();
907 }
908
937 std::optional< Entry > pop( std::size_t i );
938
941 void stop( void ) { f_stop.store( true , std::memory_order_release ); }
942
944 [[nodiscard]] bool stopped( void ) const {
945 return( f_stop.load( std::memory_order_acquire ) );
946 }
947
949 [[nodiscard]] bool terminated( void ) const {
950 return( f_active.load( std::memory_order_acquire ) == 0 );
951 }
952
955 [[nodiscard]] std::size_t steals( void ) const;
956
961 template< class E , class F >
962 void run( E & ex , F && f );
963
968 template< class F >
969 std::size_t leftovers( F && f );
970
971/*--------------------------------------------------------------------------*/
972 private:
975 struct alignas( 128 ) Worker
976 {
977 Queue q;
978 std::uint64_t x;
979 std::atomic< std::size_t > steals{ 0 };
981 Worker( const Less & less , const BdLess & bl , std::uint64_t seed )
982 : q( less , bl ) , x( seed ) { }
983 };
984
987 static std::uint64_t next( Worker & w );
988
991 std::optional< Entry > idle( std::size_t i );
992
993 std::size_t f_p;
994 Worker * f_w;
995 alignas( 128 ) std::atomic< std::int64_t > f_active;
996 alignas( 128 ) std::atomic< bool > f_stop{ false };
997
998 }; // end( class StealingFrontier )
999
1000/*--------------------------------------------------------------------------*/
1001
1002} // end( namespace ADS )
1003
1004/*--------------------------------------------------------------------------*/
1005/*-------------------------- IMPLEMENTATION --------------------------------*/
1006/*--------------------------------------------------------------------------*/
1007
1008#include "ADS/concurrent/impl/StealablePriorityQueue.tpp"
1009
1010/*--------------------------------------------------------------------------*/
1011
1012#endif /* StealablePriorityQueue.h included */
1013
1014/*--------------------------------------------------------------------------*/
1015/*------------------- End File StealablePriorityQueue.h --------------------*/
1016/*--------------------------------------------------------------------------*/
The exponential backoff of a thread that waits for a word of memory to change, beyond the book: the -...
The contracts of ADS: the preconditions, the postconditions and the invariants of the operations,...
A -ary heap of plain items, beyond the book: the heap of section 10.1 with children per node in a ve...
An allocator for the large blocks of a structure, beyond the book: a request of at least one huge pag...
The primitives of the processor that the compilers spell each in their own way, in one form for all: ...
the exact PRIORITY QUEUE of one owner, of which a thief takes about half of the pairs,...
Definition StealablePriorityQueue.h:527
std::size_t size(void) const
the number of the pairs of the queue, those of the offer included while no thief has claimed it; for ...
std::optional< Bound > minBound(void) const
the least bound of the pairs that the owner holds, nothing if it holds none: those of its two heaps a...
std::size_t steal(StealablePriorityQueue &v)
steals into this queue, empty, the offer of the queue , or asks for one and waits a little for it (a...
StealablePriorityQueue(Less less=Less(), BdLess bl=BdLess())
the empty queue of the orders less of the keys and bl of the bounds
T Item
the type of the items
Definition StealablePriorityQueue.h:532
K Key
the type of the keys
Definition StealablePriorityQueue.h:531
bool empty(void) const
whether size() is 0
Definition StealablePriorityQueue.h:719
bool offering(void) const
whether an offer of the owner waits for a thief, for the owner
bool stealable(void) const
whether the queue offers pairs or holds at least two, a hint read with no order; any thread may call ...
Definition StealablePriorityQueue.h:724
std::conditional_t< bounded, Bd, detail::SpqNoBound > Bound
the type of the bounds, detail::SpqNoBound if none
Definition StealablePriorityQueue.h:538
void serve(void)
answers a thief that asked, offering about half of the pairs if there are at least two and no offer w...
void push(K k, T x)
pushes into the smaller heap, , then answers a thief that asked
Definition StealablePriorityQueue.h:569
detail::SpqEntry< K, T, Bd > Entry
a pair of the queue: its key, its bound if any, and its item
Definition StealablePriorityQueue.h:541
StealablePriorityQueue & operator=(const StealablePriorityQueue &)=delete
no copy, since the thieves share it by its address
~StealablePriorityQueue()
the free of the offer not claimed
void push(K k, Bound b, T x)
pushes , the pair of the key with the bound , as push( k , x ) above, and into the bounds of its he...
Definition StealablePriorityQueue.h:578
std::pair< std::size_t, std::size_t > halves(void) const
the pairs that the two heaps hold, and
Definition StealablePriorityQueue.h:733
const Entry & top(void)
the least pair of the queue, the offer taken back if it holds it
std::optional< Entry > pop(void)
the least pair of the queue, removed, nothing if it is empty, after answering a thief that asked; bu...
std::size_t drain(F &&f)
the calls f( e ) on the pairs of the queue, removed, in increasing order of the keys: the offer still...
bool consistent(void) const
the two heaps ordered, and the hint of the thieves equal to their size; for the owner
static constexpr bool bounded
Definition StealablePriorityQueue.h:535
StealablePriorityQueue(const StealablePriorityQueue &)=delete
no copy, since the thieves share it by its address
void run(E &ex, F &&f)
the calls of the workers by ex.run( p , f ); the first exception of a call stops the others,...
StealingFrontier(std::size_t p, std::uint64_t seed=1, Less less=Less(), BdLess bl=BdLess())
the frontier of empty queues, the victims drawn from the seed seed
std::size_t steals(void) const
the steals that succeeded, summed over the workers, exact when no worker runs
typename Queue::Entry Entry
a pair of a queue
Definition StealablePriorityQueue.h:833
void push(std::size_t i, K k, T x)
pushes into the queue of the worker
Definition StealablePriorityQueue.h:863
std::optional< Bound > minBound(std::size_t i) const
the least bound of the pairs that the worker holds, its offer not yet claimed included,...
Definition StealablePriorityQueue.h:884
void stop(void)
ends the computation: from now on pop() returns nothing to every worker; any thread may call it
Definition StealablePriorityQueue.h:941
std::size_t leftovers(F &&f)
the calls f( e ) on the pairs left in the queues, each taken back from its offer first,...
StealingFrontier(const StealingFrontier &)=delete
no copy, since the workers share it by its address
~StealingFrontier()
the frees of the queues and of their offers
std::optional< Entry > pop(std::size_t i)
the least pair of the queue of the worker , or of what it steals when its queue is empty; nothing whe...
Queue & queue(std::size_t i)
the queue of the worker
Definition StealablePriorityQueue.h:856
std::size_t workers(void) const
the number of the workers,
Definition StealablePriorityQueue.h:852
void serve(std::size_t i)
lets the worker answer a thief in a long computation
Definition StealablePriorityQueue.h:904
typename Queue::Bound Bound
the type of the bounds, detail::SpqNoBound if none
Definition StealablePriorityQueue.h:835
StealingFrontier & operator=(const StealingFrontier &)=delete
no copy, since the workers share it by its address
bool terminated(void) const
whether no worker holds a pair, i.e.,
Definition StealablePriorityQueue.h:949
void push(std::size_t i, K k, Bound b, T x)
pushes , with the bound , into the queue of the worker
Definition StealablePriorityQueue.h:873
bool stopped(void) const
whether stop() was called
Definition StealablePriorityQueue.h:944
std::size_t drain(std::size_t i, F &&f)
the calls f( e ) on all the pairs that the worker holds, its heaps and its offer not yet claimed,...
Definition StealablePriorityQueue.h:897
[Stack]
Definition ADT.h:206
#define ADS_PRE(cond)
[check]
Definition Contract.h:121
#define ADS_SPQ_NOINLINE
a function never inlined, the rare path out of the common one
Definition StealablePriorityQueue.h:165
Definition ADT.h:96