mspriority_queue.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. // Copyright (c) 2006-2018 Maxim Khizhinsky
  2. //
  3. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. #ifndef CDSLIB_CONTAINER_MSPRIORITY_QUEUE_H
  6. #define CDSLIB_CONTAINER_MSPRIORITY_QUEUE_H
  7. #include <memory>
  8. #include <cds/container/details/base.h>
  9. #include <cds/intrusive/mspriority_queue.h>
  10. namespace cds { namespace container {
  11. /// MSPriorityQueue related definitions
  12. /** @ingroup cds_nonintrusive_helper
  13. */
  14. namespace mspriority_queue {
  15. #ifdef CDS_DOXYGEN_INVOKED
  16. /// Synonym for \p cds::intrusive::mspriority_queue::stat
  17. typedef cds::intrusive::mspriority_queue::stat<> stat;
  18. /// Synonym for \p cds::intrusive::mspriority_queue::empty_stat
  19. typedef cds::intrusive::mspriority_queue::empty_stat empty_stat;
  20. #else
  21. using cds::intrusive::mspriority_queue::stat;
  22. using cds::intrusive::mspriority_queue::empty_stat;
  23. #endif
  24. /// MSPriorityQueue traits
  25. /**
  26. The traits for \p %cds::container::MSPriorityQueue is the same as for
  27. \p cds::intrusive::MSPriorityQueue (see \p cds::intrusive::mspriority_queue::traits)
  28. plus some additional properties.
  29. */
  30. struct traits: public cds::intrusive::mspriority_queue::traits
  31. {
  32. /// The allocator use to allocate memory for values
  33. typedef CDS_DEFAULT_ALLOCATOR allocator;
  34. /// Move policy
  35. /**
  36. The move policy used in \p MSPriorityQueue::pop() function to move item's value.
  37. Default is \p opt::v::assignment_move_policy.
  38. */
  39. typedef cds::opt::v::assignment_move_policy move_policy;
  40. };
  41. /// Metafunction converting option list to traits
  42. /**
  43. \p Options are:
  44. - \p opt::buffer - the buffer type for heap array. Possible type are: \p opt::v::initiaized_static_buffer, \p opt::v::initialized_dynamic_buffer.
  45. Default is \p %opt::v::initialized_dynamic_buffer.
  46. You may specify any type of values for the buffer since at instantiation time
  47. the \p buffer::rebind member metafunction is called to change the type of values stored in the buffer.
  48. - \p opt::compare - priority compare functor. No default functor is provided.
  49. If the option is not specified, the \p opt::less is used.
  50. - \p opt::less - specifies binary predicate used for priority compare. Default is \p std::less<T>.
  51. - \p opt::lock_type - lock type. Default is \p cds::sync::spin.
  52. - \p opt::back_off - back-off strategy. Default is \p cds::backoff::yield
  53. - \p opt::allocator - allocator (like \p std::allocator) for the values of queue's items.
  54. Default is \ref CDS_DEFAULT_ALLOCATOR
  55. - \p opt::move_policy - policy for moving item's value. Default is \p opt::v::assignment_move_policy.
  56. If the compiler supports move semantics it would be better to specify the move policy
  57. based on the move semantics for type \p T.
  58. - \p opt::stat - internal statistics. Available types: \p mspriority_queue::stat, \p mspriority_queue::empty_stat (the default, no overhead)
  59. */
  60. template <typename... Options>
  61. struct make_traits {
  62. # ifdef CDS_DOXYGEN_INVOKED
  63. typedef implementation_defined type ; ///< Metafunction result
  64. # else
  65. typedef typename cds::opt::make_options<
  66. typename cds::opt::find_type_traits< traits, Options... >::type
  67. ,Options...
  68. >::type type;
  69. # endif
  70. };
  71. } // namespace mspriority_queue
  72. /// Michael & Scott array-based lock-based concurrent priority queue heap
  73. /** @ingroup cds_nonintrusive_priority_queue
  74. Source:
  75. - [1996] G.Hunt, M.Michael, S. Parthasarathy, M.Scott
  76. "An efficient algorithm for concurrent priority queue heaps"
  77. \p %MSPriorityQueue augments the standard array-based heap data structure with
  78. a mutual-exclusion lock on the heap's size and locks on each node in the heap.
  79. Each node also has a tag that indicates whether
  80. it is empty, valid, or in a transient state due to an update to the heap
  81. by an inserting thread.
  82. The algorithm allows concurrent insertions and deletions in opposite directions,
  83. without risking deadlock and without the need for special server threads.
  84. It also uses a "bit-reversal" technique to scatter accesses across the fringe
  85. of the tree to reduce contention.
  86. On large heaps the algorithm achieves significant performance improvements
  87. over serialized single-lock algorithm, for various insertion/deletion
  88. workloads. For small heaps it still performs well, but not as well as
  89. single-lock algorithm.
  90. Template parameters:
  91. - \p T - type to be stored in the list. The priority is a part of \p T type.
  92. - \p Traits - the traits. See \p mspriority_queue::traits for explanation.
  93. It is possible to declare option-based queue with \p mspriority_queue::make_traits
  94. metafunction instead of \p Traits template argument.
  95. */
  96. template <typename T, class Traits = mspriority_queue::traits >
  97. class MSPriorityQueue: protected cds::intrusive::MSPriorityQueue< T, Traits >
  98. {
  99. //@cond
  100. typedef cds::intrusive::MSPriorityQueue< T, Traits > base_class;
  101. //@endcond
  102. public:
  103. typedef T value_type ; ///< Value type stored in the queue
  104. typedef Traits traits ; ///< Traits template parameter
  105. typedef typename base_class::key_comparator key_comparator; ///< priority comparing functor based on opt::compare and opt::less option setter.
  106. typedef typename base_class::lock_type lock_type; ///< heap's size lock type
  107. typedef typename base_class::back_off back_off ; ///< Back-off strategy
  108. typedef typename traits::stat stat; ///< internal statistics type, see \p intrusive::mspriority_queue::traits::stat
  109. typedef typename base_class::item_counter item_counter;///< Item counter type
  110. typedef typename std::allocator_traits<typename traits::allocator>::template rebind_alloc<value_type> allocator_type; ///< Value allocator
  111. typedef typename traits::move_policy move_policy; ///< Move policy for type \p T
  112. protected:
  113. //@cond
  114. typedef cds::details::Allocator< value_type, allocator_type > cxx_allocator;
  115. struct value_deleter {
  116. void operator()( value_type * p ) const
  117. {
  118. cxx_allocator().Delete( p );
  119. }
  120. };
  121. typedef std::unique_ptr<value_type, value_deleter> scoped_ptr;
  122. //@endcond
  123. public:
  124. /// Constructs empty priority queue
  125. /**
  126. For \p cds::opt::v::initialized_static_buffer the \p nCapacity parameter is ignored.
  127. */
  128. MSPriorityQueue( size_t nCapacity )
  129. : base_class( nCapacity )
  130. {}
  131. /// Clears priority queue and destructs the object
  132. ~MSPriorityQueue()
  133. {
  134. clear();
  135. }
  136. /// Inserts an item into priority queue
  137. /**
  138. If the priority queue is full, the function returns \p false,
  139. no item has been added.
  140. Otherwise, the function inserts the copy of \p val into the heap
  141. and returns \p true.
  142. The function use copy constructor to create new heap item from \p val.
  143. */
  144. bool push( value_type const& val )
  145. {
  146. scoped_ptr pVal( cxx_allocator().New( val ));
  147. if ( base_class::push( *(pVal.get()))) {
  148. pVal.release();
  149. return true;
  150. }
  151. return false;
  152. }
  153. /// Inserts an item into the queue using a functor
  154. /**
  155. \p Func is a functor called to create node.
  156. The functor \p f takes one argument - a reference to a new node of type \ref value_type :
  157. \code
  158. cds::container::MSPriorityQueue< Foo > myQueue;
  159. Bar bar;
  160. myQueue.push_with( [&bar]( Foo& dest ) { dest = bar; } );
  161. \endcode
  162. */
  163. template <typename Func>
  164. bool push_with( Func f )
  165. {
  166. scoped_ptr pVal( cxx_allocator().New());
  167. f( *pVal );
  168. if ( base_class::push( *pVal )) {
  169. pVal.release();
  170. return true;
  171. }
  172. return false;
  173. }
  174. /// Inserts a item into priority queue
  175. /**
  176. If the priority queue is full, the function returns \p false,
  177. no item has been added.
  178. Otherwise, the function inserts a new item created from \p args arguments
  179. into the heap and returns \p true.
  180. */
  181. template <typename... Args>
  182. bool emplace( Args&&... args )
  183. {
  184. scoped_ptr pVal( cxx_allocator().MoveNew( std::forward<Args>(args)... ));
  185. if ( base_class::push( *(pVal.get()))) {
  186. pVal.release();
  187. return true;
  188. }
  189. return false;
  190. }
  191. /// Extracts item with high priority
  192. /**
  193. If the priority queue is empty, the function returns \p false.
  194. Otherwise, it returns \p true and \p dest contains the copy of extracted item.
  195. The item is deleted from the heap.
  196. The function uses \ref move_policy to move extracted value from the heap's top
  197. to \p dest.
  198. The function is equivalent of such call:
  199. \code
  200. pop_with( dest, [&dest]( value_type& src ) { move_policy()(dest, src); } );
  201. \endcode
  202. */
  203. bool pop( value_type& dest )
  204. {
  205. return pop_with( [&dest]( value_type& src ) { move_policy()(dest, std::move(src)); });
  206. }
  207. /// Extracts an item with high priority
  208. /**
  209. If the priority queue is empty, the function returns \p false.
  210. Otherwise, it returns \p true and \p dest contains the copy of extracted item.
  211. The item is deleted from the heap.
  212. \p Func is a functor called to copy popped value.
  213. The functor takes one argument - a reference to removed node:
  214. \code
  215. cds:container::MSPriorityQueue< Foo > myQueue;
  216. Bar bar;
  217. myQueue.pop_with( [&bar]( Foo& src ) { bar = std::move( src );});
  218. \endcode
  219. */
  220. template <typename Func>
  221. bool pop_with( Func f )
  222. {
  223. value_type * pVal = base_class::pop();
  224. if ( pVal ) {
  225. f( *pVal );
  226. cxx_allocator().Delete( pVal );
  227. return true;
  228. }
  229. return false;
  230. }
  231. /// Clears the queue (not atomic)
  232. /**
  233. This function is not atomic, but thread-safe
  234. */
  235. void clear()
  236. {
  237. base_class::clear_with( []( value_type& src ) { value_deleter()(&src); } );
  238. }
  239. /// Clears the queue (not atomic)
  240. /**
  241. This function is not atomic, but thread-safe.
  242. For each item removed the functor \p f is called.
  243. \p Func interface is:
  244. \code
  245. struct clear_functor
  246. {
  247. void operator()( value_type& item );
  248. };
  249. \endcode
  250. */
  251. template <typename Func>
  252. void clear_with( Func f )
  253. {
  254. base_class::clear_with( [&f]( value_type& val ) { f(val); value_deleter()( &val ); } );
  255. }
  256. /// Checks is the priority queue is empty
  257. bool empty() const
  258. {
  259. return base_class::empty();
  260. }
  261. /// Checks if the priority queue is full
  262. bool full() const
  263. {
  264. return base_class::full();
  265. }
  266. /// Returns current size of priority queue
  267. size_t size() const
  268. {
  269. return base_class::size();
  270. }
  271. /// Return capacity of the priority queue
  272. size_t capacity() const
  273. {
  274. return base_class::capacity();
  275. }
  276. /// Returns const reference to internal statistics
  277. stat const& statistics() const
  278. {
  279. return base_class::statistics();
  280. }
  281. };
  282. }} // namespace cds::container
  283. #endif // #ifndef CDSLIB_CONTAINER_MSPRIORITY_QUEUE_H