message_queue.hpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. //////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost
  4. // Software License, Version 1.0. (See accompanying file
  5. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. // See http://www.boost.org/libs/interprocess for documentation.
  8. //
  9. //////////////////////////////////////////////////////////////////////////////
  10. #ifndef BOOST_INTERPROCESS_MESSAGE_QUEUE_HPP
  11. #define BOOST_INTERPROCESS_MESSAGE_QUEUE_HPP
  12. #ifndef BOOST_CONFIG_HPP
  13. # include <boost/config.hpp>
  14. #endif
  15. #
  16. #if defined(BOOST_HAS_PRAGMA_ONCE)
  17. # pragma once
  18. #endif
  19. #include <boost/interprocess/detail/config_begin.hpp>
  20. #include <boost/interprocess/detail/workaround.hpp>
  21. #include <boost/interprocess/shared_memory_object.hpp>
  22. #include <boost/interprocess/detail/managed_open_or_create_impl.hpp>
  23. #include <boost/interprocess/sync/interprocess_condition.hpp>
  24. #include <boost/interprocess/sync/interprocess_mutex.hpp>
  25. #include <boost/interprocess/sync/scoped_lock.hpp>
  26. #include <boost/interprocess/detail/utilities.hpp>
  27. #include <boost/interprocess/offset_ptr.hpp>
  28. #include <boost/interprocess/creation_tags.hpp>
  29. #include <boost/interprocess/exceptions.hpp>
  30. #include <boost/interprocess/permissions.hpp>
  31. #include <boost/core/no_exceptions_support.hpp>
  32. #include <boost/interprocess/detail/type_traits.hpp>
  33. #include <boost/intrusive/pointer_traits.hpp>
  34. #include <boost/move/detail/type_traits.hpp> //make_unsigned, alignment_of
  35. #include <boost/intrusive/pointer_traits.hpp>
  36. #include <boost/assert.hpp>
  37. #include <algorithm> //std::lower_bound
  38. #include <cstddef> //std::size_t
  39. #include <cstring> //memcpy
  40. //!\file
  41. //!Describes an inter-process message queue. This class allows sending
  42. //!messages between processes and allows blocking, non-blocking and timed
  43. //!sending and receiving.
  44. namespace boost{ namespace interprocess{
  45. namespace ipcdetail
  46. {
  47. template<class VoidPointer>
  48. class msg_queue_initialization_func_t;
  49. }
  50. //!A class that allows sending messages
  51. //!between processes.
  52. template<class VoidPointer>
  53. class message_queue_t
  54. {
  55. #if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)
  56. //Blocking modes
  57. enum block_t { blocking, timed, non_blocking };
  58. message_queue_t();
  59. #endif //#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED
  60. public:
  61. typedef VoidPointer void_pointer;
  62. typedef typename boost::intrusive::
  63. pointer_traits<void_pointer>::template
  64. rebind_pointer<char>::type char_ptr;
  65. typedef typename boost::intrusive::pointer_traits<char_ptr>::difference_type difference_type;
  66. typedef typename boost::container::dtl::make_unsigned<difference_type>::type size_type;
  67. //!Creates a process shared message queue with name "name". For this message queue,
  68. //!the maximum number of messages will be "max_num_msg" and the maximum message size
  69. //!will be "max_msg_size". Throws on error and if the queue was previously created.
  70. message_queue_t(create_only_t create_only,
  71. const char *name,
  72. size_type max_num_msg,
  73. size_type max_msg_size,
  74. const permissions &perm = permissions());
  75. //!Opens or creates a process shared message queue with name "name".
  76. //!If the queue is created, the maximum number of messages will be "max_num_msg"
  77. //!and the maximum message size will be "max_msg_size". If queue was previously
  78. //!created the queue will be opened and "max_num_msg" and "max_msg_size" parameters
  79. //!are ignored. Throws on error.
  80. message_queue_t(open_or_create_t open_or_create,
  81. const char *name,
  82. size_type max_num_msg,
  83. size_type max_msg_size,
  84. const permissions &perm = permissions());
  85. //!Opens a previously created process shared message queue with name "name".
  86. //!If the queue was not previously created or there are no free resources,
  87. //!throws an error.
  88. message_queue_t(open_only_t open_only,
  89. const char *name);
  90. //!Destroys *this and indicates that the calling process is finished using
  91. //!the resource. All opened message queues are still
  92. //!valid after destruction. The destructor function will deallocate
  93. //!any system resources allocated by the system for use by this process for
  94. //!this resource. The resource can still be opened again calling
  95. //!the open constructor overload. To erase the message queue from the system
  96. //!use remove().
  97. ~message_queue_t();
  98. //!Sends a message stored in buffer "buffer" with size "buffer_size" in the
  99. //!message queue with priority "priority". If the message queue is full
  100. //!the sender is blocked. Throws interprocess_error on error.
  101. void send (const void *buffer, size_type buffer_size,
  102. unsigned int priority);
  103. //!Sends a message stored in buffer "buffer" with size "buffer_size" through the
  104. //!message queue with priority "priority". If the message queue is full
  105. //!the sender is not blocked and returns false, otherwise returns true.
  106. //!Throws interprocess_error on error.
  107. bool try_send (const void *buffer, size_type buffer_size,
  108. unsigned int priority);
  109. //!Sends a message stored in buffer "buffer" with size "buffer_size" in the
  110. //!message queue with priority "priority". If the message queue is full
  111. //!the sender retries until time "abs_time" is reached. Returns true if
  112. //!the message has been successfully sent. Returns false if timeout is reached.
  113. //!Throws interprocess_error on error.
  114. bool timed_send (const void *buffer, size_type buffer_size,
  115. unsigned int priority, const boost::posix_time::ptime& abs_time);
  116. //!Receives a message from the message queue. The message is stored in buffer
  117. //!"buffer", which has size "buffer_size". The received message has size
  118. //!"recvd_size" and priority "priority". If the message queue is empty
  119. //!the receiver is blocked. Throws interprocess_error on error.
  120. void receive (void *buffer, size_type buffer_size,
  121. size_type &recvd_size,unsigned int &priority);
  122. //!Receives a message from the message queue. The message is stored in buffer
  123. //!"buffer", which has size "buffer_size". The received message has size
  124. //!"recvd_size" and priority "priority". If the message queue is empty
  125. //!the receiver is not blocked and returns false, otherwise returns true.
  126. //!Throws interprocess_error on error.
  127. bool try_receive (void *buffer, size_type buffer_size,
  128. size_type &recvd_size,unsigned int &priority);
  129. //!Receives a message from the message queue. The message is stored in buffer
  130. //!"buffer", which has size "buffer_size". The received message has size
  131. //!"recvd_size" and priority "priority". If the message queue is empty
  132. //!the receiver retries until time "abs_time" is reached. Returns true if
  133. //!the message has been successfully sent. Returns false if timeout is reached.
  134. //!Throws interprocess_error on error.
  135. bool timed_receive (void *buffer, size_type buffer_size,
  136. size_type &recvd_size,unsigned int &priority,
  137. const boost::posix_time::ptime &abs_time);
  138. //!Returns the maximum number of messages allowed by the queue. The message
  139. //!queue must be opened or created previously. Otherwise, returns 0.
  140. //!Never throws
  141. size_type get_max_msg() const;
  142. //!Returns the maximum size of message allowed by the queue. The message
  143. //!queue must be opened or created previously. Otherwise, returns 0.
  144. //!Never throws
  145. size_type get_max_msg_size() const;
  146. //!Returns the number of messages currently stored.
  147. //!Never throws
  148. size_type get_num_msg() const;
  149. //!Removes the message queue from the system.
  150. //!Returns false on error. Never throws
  151. static bool remove(const char *name);
  152. #if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)
  153. private:
  154. typedef boost::posix_time::ptime ptime;
  155. friend class ipcdetail::msg_queue_initialization_func_t<VoidPointer>;
  156. bool do_receive(block_t block,
  157. void *buffer, size_type buffer_size,
  158. size_type &recvd_size, unsigned int &priority,
  159. const ptime &abs_time);
  160. bool do_send(block_t block,
  161. const void *buffer, size_type buffer_size,
  162. unsigned int priority, const ptime &abs_time);
  163. //!Returns the needed memory size for the shared message queue.
  164. //!Never throws
  165. static size_type get_mem_size(size_type max_msg_size, size_type max_num_msg);
  166. typedef ipcdetail::managed_open_or_create_impl<shared_memory_object, 0, true, false> open_create_impl_t;
  167. open_create_impl_t m_shmem;
  168. #endif //#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED
  169. };
  170. #if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)
  171. namespace ipcdetail {
  172. //!This header is the prefix of each message in the queue
  173. template<class VoidPointer>
  174. class msg_hdr_t
  175. {
  176. typedef VoidPointer void_pointer;
  177. typedef typename boost::intrusive::
  178. pointer_traits<void_pointer>::template
  179. rebind_pointer<char>::type char_ptr;
  180. typedef typename boost::intrusive::pointer_traits<char_ptr>::difference_type difference_type;
  181. typedef typename boost::container::dtl::make_unsigned<difference_type>::type size_type;
  182. public:
  183. size_type len; // Message length
  184. unsigned int priority;// Message priority
  185. //!Returns the data buffer associated with this this message
  186. void * data(){ return this+1; } //
  187. };
  188. //!This functor is the predicate to order stored messages by priority
  189. template<class VoidPointer>
  190. class priority_functor
  191. {
  192. typedef typename boost::intrusive::
  193. pointer_traits<VoidPointer>::template
  194. rebind_pointer<msg_hdr_t<VoidPointer> >::type msg_hdr_ptr_t;
  195. public:
  196. bool operator()(const msg_hdr_ptr_t &msg1,
  197. const msg_hdr_ptr_t &msg2) const
  198. { return msg1->priority < msg2->priority; }
  199. };
  200. //!This header is placed in the beginning of the shared memory and contains
  201. //!the data to control the queue. This class initializes the shared memory
  202. //!in the following way: in ascending memory address with proper alignment
  203. //!fillings:
  204. //!
  205. //!-> mq_hdr_t:
  206. //! Main control block that controls the rest of the elements
  207. //!
  208. //!-> offset_ptr<msg_hdr_t> index [max_num_msg]
  209. //! An array of pointers with size "max_num_msg" called index. Each pointer
  210. //! points to a preallocated message. Elements of this array are
  211. //! reordered in runtime in the following way:
  212. //!
  213. //! IF BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX is defined:
  214. //!
  215. //! When the current number of messages is "cur_num_msg", the array
  216. //! is treated like a circular buffer. Starting from position "cur_first_msg"
  217. //! "cur_num_msg" in a circular way, pointers point to inserted messages and the rest
  218. //! point to free messages. Those "cur_num_msg" pointers are
  219. //! ordered by the priority of the pointed message and by insertion order
  220. //! if two messages have the same priority. So the next message to be
  221. //! used in a "receive" is pointed by index [(cur_first_msg + cur_num_msg-1)%max_num_msg]
  222. //! and the first free message ready to be used in a "send" operation is
  223. //! [cur_first_msg] if circular buffer is extended from front,
  224. //! [(cur_first_msg + cur_num_msg)%max_num_msg] otherwise.
  225. //!
  226. //! This transforms the index in a circular buffer with an embedded free
  227. //! message queue.
  228. //!
  229. //! ELSE (BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX is NOT defined):
  230. //!
  231. //! When the current number of messages is "cur_num_msg", the first
  232. //! "cur_num_msg" pointers point to inserted messages and the rest
  233. //! point to free messages. The first "cur_num_msg" pointers are
  234. //! ordered by the priority of the pointed message and by insertion order
  235. //! if two messages have the same priority. So the next message to be
  236. //! used in a "receive" is pointed by index [cur_num_msg-1] and the first free
  237. //! message ready to be used in a "send" operation is index [cur_num_msg].
  238. //!
  239. //! This transforms the index in a fixed size priority queue with an embedded free
  240. //! message queue.
  241. //!
  242. //!-> struct message_t
  243. //! {
  244. //! msg_hdr_t header;
  245. //! char[max_msg_size] data;
  246. //! } messages [max_num_msg];
  247. //!
  248. //! An array of buffers of preallocated messages, each one prefixed with the
  249. //! msg_hdr_t structure. Each of this message is pointed by one pointer of
  250. //! the index structure.
  251. template<class VoidPointer>
  252. class mq_hdr_t
  253. : public ipcdetail::priority_functor<VoidPointer>
  254. {
  255. typedef VoidPointer void_pointer;
  256. typedef msg_hdr_t<void_pointer> msg_header;
  257. typedef typename boost::intrusive::
  258. pointer_traits<void_pointer>::template
  259. rebind_pointer<msg_header>::type msg_hdr_ptr_t;
  260. typedef typename boost::intrusive::pointer_traits
  261. <msg_hdr_ptr_t>::difference_type difference_type;
  262. typedef typename boost::container::
  263. dtl::make_unsigned<difference_type>::type size_type;
  264. typedef typename boost::intrusive::
  265. pointer_traits<void_pointer>::template
  266. rebind_pointer<msg_hdr_ptr_t>::type msg_hdr_ptr_ptr_t;
  267. typedef ipcdetail::managed_open_or_create_impl<shared_memory_object, 0, true, false> open_create_impl_t;
  268. public:
  269. //!Constructor. This object must be constructed in the beginning of the
  270. //!shared memory of the size returned by the function "get_mem_size".
  271. //!This constructor initializes the needed resources and creates
  272. //!the internal structures like the priority index. This can throw.
  273. mq_hdr_t(size_type max_num_msg, size_type max_msg_size)
  274. : m_max_num_msg(max_num_msg),
  275. m_max_msg_size(max_msg_size),
  276. m_cur_num_msg(0)
  277. #if defined(BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX)
  278. ,m_cur_first_msg(0u)
  279. ,m_blocked_senders(0u)
  280. ,m_blocked_receivers(0u)
  281. #endif
  282. { this->initialize_memory(); }
  283. //!Returns true if the message queue is full
  284. bool is_full() const
  285. { return m_cur_num_msg == m_max_num_msg; }
  286. //!Returns true if the message queue is empty
  287. bool is_empty() const
  288. { return !m_cur_num_msg; }
  289. //!Frees the top priority message and saves it in the free message list
  290. void free_top_msg()
  291. { --m_cur_num_msg; }
  292. #if defined(BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX)
  293. typedef msg_hdr_ptr_t *iterator;
  294. size_type end_pos() const
  295. {
  296. const size_type space_until_bufend = m_max_num_msg - m_cur_first_msg;
  297. return space_until_bufend > m_cur_num_msg
  298. ? m_cur_first_msg + m_cur_num_msg : m_cur_num_msg - space_until_bufend;
  299. }
  300. //!Returns the inserted message with top priority
  301. msg_header &top_msg()
  302. {
  303. size_type pos = this->end_pos();
  304. return *mp_index[pos ? --pos : m_max_num_msg - 1];
  305. }
  306. //!Returns the inserted message with bottom priority
  307. msg_header &bottom_msg()
  308. { return *mp_index[m_cur_first_msg]; }
  309. iterator inserted_ptr_begin() const
  310. { return &mp_index[m_cur_first_msg]; }
  311. iterator inserted_ptr_end() const
  312. { return &mp_index[this->end_pos()]; }
  313. iterator lower_bound(const msg_hdr_ptr_t & value, priority_functor<VoidPointer> func)
  314. {
  315. iterator begin(this->inserted_ptr_begin()), end(this->inserted_ptr_end());
  316. if(end < begin){
  317. iterator idx_end = &mp_index[m_max_num_msg];
  318. iterator ret = std::lower_bound(begin, idx_end, value, func);
  319. if(idx_end == ret){
  320. iterator idx_beg = &mp_index[0];
  321. ret = std::lower_bound(idx_beg, end, value, func);
  322. //sanity check, these cases should not call lower_bound (optimized out)
  323. BOOST_ASSERT(ret != end);
  324. BOOST_ASSERT(ret != begin);
  325. return ret;
  326. }
  327. else{
  328. return ret;
  329. }
  330. }
  331. else{
  332. return std::lower_bound(begin, end, value, func);
  333. }
  334. }
  335. msg_header & insert_at(iterator where)
  336. {
  337. iterator it_inserted_ptr_end = this->inserted_ptr_end();
  338. iterator it_inserted_ptr_beg = this->inserted_ptr_begin();
  339. if(where == it_inserted_ptr_beg){
  340. //unsigned integer guarantees underflow
  341. m_cur_first_msg = m_cur_first_msg ? m_cur_first_msg : m_max_num_msg;
  342. --m_cur_first_msg;
  343. ++m_cur_num_msg;
  344. return *mp_index[m_cur_first_msg];
  345. }
  346. else if(where == it_inserted_ptr_end){
  347. ++m_cur_num_msg;
  348. return **it_inserted_ptr_end;
  349. }
  350. else{
  351. size_type pos = where - &mp_index[0];
  352. size_type circ_pos = pos >= m_cur_first_msg ? pos - m_cur_first_msg : pos + (m_max_num_msg - m_cur_first_msg);
  353. //Check if it's more efficient to move back or move front
  354. if(circ_pos < m_cur_num_msg/2){
  355. //The queue can't be full so m_cur_num_msg == 0 or m_cur_num_msg <= pos
  356. //indicates two step insertion
  357. if(!pos){
  358. pos = m_max_num_msg;
  359. where = &mp_index[m_max_num_msg-1];
  360. }
  361. else{
  362. --where;
  363. }
  364. const bool unique_segment = m_cur_first_msg && m_cur_first_msg <= pos;
  365. const size_type first_segment_beg = unique_segment ? m_cur_first_msg : 1u;
  366. const size_type first_segment_end = pos;
  367. const size_type second_segment_beg = unique_segment || !m_cur_first_msg ? m_max_num_msg : m_cur_first_msg;
  368. const size_type second_segment_end = m_max_num_msg;
  369. const msg_hdr_ptr_t backup = *(&mp_index[0] + (unique_segment ? first_segment_beg : second_segment_beg) - 1);
  370. //First segment
  371. if(!unique_segment){
  372. std::copy( &mp_index[0] + second_segment_beg
  373. , &mp_index[0] + second_segment_end
  374. , &mp_index[0] + second_segment_beg - 1);
  375. mp_index[m_max_num_msg-1] = mp_index[0];
  376. }
  377. std::copy( &mp_index[0] + first_segment_beg
  378. , &mp_index[0] + first_segment_end
  379. , &mp_index[0] + first_segment_beg - 1);
  380. *where = backup;
  381. m_cur_first_msg = m_cur_first_msg ? m_cur_first_msg : m_max_num_msg;
  382. --m_cur_first_msg;
  383. ++m_cur_num_msg;
  384. return **where;
  385. }
  386. else{
  387. //The queue can't be full so end_pos < m_cur_first_msg
  388. //indicates two step insertion
  389. const size_type pos_end = this->end_pos();
  390. const bool unique_segment = pos < pos_end;
  391. const size_type first_segment_beg = pos;
  392. const size_type first_segment_end = unique_segment ? pos_end : m_max_num_msg-1;
  393. const size_type second_segment_beg = 0u;
  394. const size_type second_segment_end = unique_segment ? 0u : pos_end;
  395. const msg_hdr_ptr_t backup = *it_inserted_ptr_end;
  396. //First segment
  397. if(!unique_segment){
  398. std::copy_backward( &mp_index[0] + second_segment_beg
  399. , &mp_index[0] + second_segment_end
  400. , &mp_index[0] + second_segment_end + 1);
  401. mp_index[0] = mp_index[m_max_num_msg-1];
  402. }
  403. std::copy_backward( &mp_index[0] + first_segment_beg
  404. , &mp_index[0] + first_segment_end
  405. , &mp_index[0] + first_segment_end + 1);
  406. *where = backup;
  407. ++m_cur_num_msg;
  408. return **where;
  409. }
  410. }
  411. }
  412. #else //BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX
  413. typedef msg_hdr_ptr_t *iterator;
  414. //!Returns the inserted message with top priority
  415. msg_header &top_msg()
  416. { return *mp_index[m_cur_num_msg-1]; }
  417. //!Returns the inserted message with bottom priority
  418. msg_header &bottom_msg()
  419. { return *mp_index[0]; }
  420. iterator inserted_ptr_begin() const
  421. { return &mp_index[0]; }
  422. iterator inserted_ptr_end() const
  423. { return &mp_index[m_cur_num_msg]; }
  424. iterator lower_bound(const msg_hdr_ptr_t & value, priority_functor<VoidPointer> func)
  425. { return std::lower_bound(this->inserted_ptr_begin(), this->inserted_ptr_end(), value, func); }
  426. msg_header & insert_at(iterator pos)
  427. {
  428. const msg_hdr_ptr_t backup = *inserted_ptr_end();
  429. std::copy_backward(pos, inserted_ptr_end(), inserted_ptr_end()+1);
  430. *pos = backup;
  431. ++m_cur_num_msg;
  432. return **pos;
  433. }
  434. #endif //BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX
  435. //!Inserts the first free message in the priority queue
  436. msg_header & queue_free_msg(unsigned int priority)
  437. {
  438. //Get priority queue's range
  439. iterator it (inserted_ptr_begin()), it_end(inserted_ptr_end());
  440. //Optimize for non-priority usage
  441. if(m_cur_num_msg && priority > this->bottom_msg().priority){
  442. //Check for higher priority than all stored messages
  443. if(priority > this->top_msg().priority){
  444. it = it_end;
  445. }
  446. else{
  447. //Since we don't now which free message we will pick
  448. //build a dummy header for searches
  449. msg_header dummy_hdr;
  450. dummy_hdr.priority = priority;
  451. //Get free msg
  452. msg_hdr_ptr_t dummy_ptr(&dummy_hdr);
  453. //Check where the free message should be placed
  454. it = this->lower_bound(dummy_ptr, static_cast<priority_functor<VoidPointer>&>(*this));
  455. }
  456. }
  457. //Insert the free message in the correct position
  458. return this->insert_at(it);
  459. }
  460. //!Returns the number of bytes needed to construct a message queue with
  461. //!"max_num_size" maximum number of messages and "max_msg_size" maximum
  462. //!message size. Never throws.
  463. static size_type get_mem_size
  464. (size_type max_msg_size, size_type max_num_msg)
  465. {
  466. const size_type
  467. msg_hdr_align = ::boost::container::dtl::alignment_of<msg_header>::value,
  468. index_align = ::boost::container::dtl::alignment_of<msg_hdr_ptr_t>::value,
  469. r_hdr_size = ipcdetail::ct_rounded_size<sizeof(mq_hdr_t), index_align>::value,
  470. r_index_size = ipcdetail::get_rounded_size<size_type>(max_num_msg*sizeof(msg_hdr_ptr_t), msg_hdr_align),
  471. r_max_msg_size = ipcdetail::get_rounded_size<size_type>(max_msg_size, msg_hdr_align) + sizeof(msg_header);
  472. return r_hdr_size + r_index_size + (max_num_msg*r_max_msg_size) +
  473. open_create_impl_t::ManagedOpenOrCreateUserOffset;
  474. }
  475. //!Initializes the memory structures to preallocate messages and constructs the
  476. //!message index. Never throws.
  477. void initialize_memory()
  478. {
  479. const size_type
  480. msg_hdr_align = ::boost::container::dtl::alignment_of<msg_header>::value,
  481. index_align = ::boost::container::dtl::alignment_of<msg_hdr_ptr_t>::value,
  482. r_hdr_size = ipcdetail::ct_rounded_size<sizeof(mq_hdr_t), index_align>::value,
  483. r_index_size = ipcdetail::get_rounded_size<size_type>(m_max_num_msg*sizeof(msg_hdr_ptr_t), msg_hdr_align),
  484. r_max_msg_size = ipcdetail::get_rounded_size<size_type>(m_max_msg_size, msg_hdr_align) + sizeof(msg_header);
  485. //Pointer to the index
  486. msg_hdr_ptr_t *index = reinterpret_cast<msg_hdr_ptr_t*>
  487. (reinterpret_cast<char*>(this)+r_hdr_size);
  488. //Pointer to the first message header
  489. msg_header *msg_hdr = reinterpret_cast<msg_header*>
  490. (reinterpret_cast<char*>(this)+r_hdr_size+r_index_size);
  491. //Initialize the pointer to the index
  492. mp_index = index;
  493. //Initialize the index so each slot points to a preallocated message
  494. for(size_type i = 0; i < m_max_num_msg; ++i){
  495. index[i] = msg_hdr;
  496. msg_hdr = reinterpret_cast<msg_header*>
  497. (reinterpret_cast<char*>(msg_hdr)+r_max_msg_size);
  498. }
  499. }
  500. public:
  501. //Pointer to the index
  502. msg_hdr_ptr_ptr_t mp_index;
  503. //Maximum number of messages of the queue
  504. const size_type m_max_num_msg;
  505. //Maximum size of messages of the queue
  506. const size_type m_max_msg_size;
  507. //Current number of messages
  508. size_type m_cur_num_msg;
  509. //Mutex to protect data structures
  510. interprocess_mutex m_mutex;
  511. //Condition block receivers when there are no messages
  512. interprocess_condition m_cond_recv;
  513. //Condition block senders when the queue is full
  514. interprocess_condition m_cond_send;
  515. #if defined(BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX)
  516. //Current start offset in the circular index
  517. size_type m_cur_first_msg;
  518. size_type m_blocked_senders;
  519. size_type m_blocked_receivers;
  520. #endif
  521. };
  522. //!This is the atomic functor to be executed when creating or opening
  523. //!shared memory. Never throws
  524. template<class VoidPointer>
  525. class msg_queue_initialization_func_t
  526. {
  527. public:
  528. typedef typename boost::intrusive::
  529. pointer_traits<VoidPointer>::template
  530. rebind_pointer<char>::type char_ptr;
  531. typedef typename boost::intrusive::pointer_traits<char_ptr>::
  532. difference_type difference_type;
  533. typedef typename boost::container::dtl::
  534. make_unsigned<difference_type>::type size_type;
  535. msg_queue_initialization_func_t(size_type maxmsg = 0,
  536. size_type maxmsgsize = 0)
  537. : m_maxmsg (maxmsg), m_maxmsgsize(maxmsgsize) {}
  538. bool operator()(void *address, size_type, bool created)
  539. {
  540. char *mptr;
  541. if(created){
  542. mptr = reinterpret_cast<char*>(address);
  543. //Construct the message queue header at the beginning
  544. BOOST_TRY{
  545. new (mptr) mq_hdr_t<VoidPointer>(m_maxmsg, m_maxmsgsize);
  546. }
  547. BOOST_CATCH(...){
  548. return false;
  549. }
  550. BOOST_CATCH_END
  551. }
  552. return true;
  553. }
  554. std::size_t get_min_size() const
  555. {
  556. return mq_hdr_t<VoidPointer>::get_mem_size(m_maxmsgsize, m_maxmsg)
  557. - message_queue_t<VoidPointer>::open_create_impl_t::ManagedOpenOrCreateUserOffset;
  558. }
  559. const size_type m_maxmsg;
  560. const size_type m_maxmsgsize;
  561. };
  562. } //namespace ipcdetail {
  563. template<class VoidPointer>
  564. inline message_queue_t<VoidPointer>::~message_queue_t()
  565. {}
  566. template<class VoidPointer>
  567. inline typename message_queue_t<VoidPointer>::size_type message_queue_t<VoidPointer>::get_mem_size
  568. (size_type max_msg_size, size_type max_num_msg)
  569. { return ipcdetail::mq_hdr_t<VoidPointer>::get_mem_size(max_msg_size, max_num_msg); }
  570. template<class VoidPointer>
  571. inline message_queue_t<VoidPointer>::message_queue_t(create_only_t,
  572. const char *name,
  573. size_type max_num_msg,
  574. size_type max_msg_size,
  575. const permissions &perm)
  576. //Create shared memory and execute functor atomically
  577. : m_shmem(create_only,
  578. name,
  579. get_mem_size(max_msg_size, max_num_msg),
  580. read_write,
  581. static_cast<void*>(0),
  582. //Prepare initialization functor
  583. ipcdetail::msg_queue_initialization_func_t<VoidPointer> (max_num_msg, max_msg_size),
  584. perm)
  585. {}
  586. template<class VoidPointer>
  587. inline message_queue_t<VoidPointer>::message_queue_t(open_or_create_t,
  588. const char *name,
  589. size_type max_num_msg,
  590. size_type max_msg_size,
  591. const permissions &perm)
  592. //Create shared memory and execute functor atomically
  593. : m_shmem(open_or_create,
  594. name,
  595. get_mem_size(max_msg_size, max_num_msg),
  596. read_write,
  597. static_cast<void*>(0),
  598. //Prepare initialization functor
  599. ipcdetail::msg_queue_initialization_func_t<VoidPointer> (max_num_msg, max_msg_size),
  600. perm)
  601. {}
  602. template<class VoidPointer>
  603. inline message_queue_t<VoidPointer>::message_queue_t(open_only_t, const char *name)
  604. //Create shared memory and execute functor atomically
  605. : m_shmem(open_only,
  606. name,
  607. read_write,
  608. static_cast<void*>(0),
  609. //Prepare initialization functor
  610. ipcdetail::msg_queue_initialization_func_t<VoidPointer> ())
  611. {}
  612. template<class VoidPointer>
  613. inline void message_queue_t<VoidPointer>::send
  614. (const void *buffer, size_type buffer_size, unsigned int priority)
  615. { this->do_send(blocking, buffer, buffer_size, priority, ptime()); }
  616. template<class VoidPointer>
  617. inline bool message_queue_t<VoidPointer>::try_send
  618. (const void *buffer, size_type buffer_size, unsigned int priority)
  619. { return this->do_send(non_blocking, buffer, buffer_size, priority, ptime()); }
  620. template<class VoidPointer>
  621. inline bool message_queue_t<VoidPointer>::timed_send
  622. (const void *buffer, size_type buffer_size
  623. ,unsigned int priority, const boost::posix_time::ptime &abs_time)
  624. {
  625. if(abs_time == boost::posix_time::pos_infin){
  626. this->send(buffer, buffer_size, priority);
  627. return true;
  628. }
  629. return this->do_send(timed, buffer, buffer_size, priority, abs_time);
  630. }
  631. template<class VoidPointer>
  632. inline bool message_queue_t<VoidPointer>::do_send(block_t block,
  633. const void *buffer, size_type buffer_size,
  634. unsigned int priority, const boost::posix_time::ptime &abs_time)
  635. {
  636. ipcdetail::mq_hdr_t<VoidPointer> *p_hdr = static_cast<ipcdetail::mq_hdr_t<VoidPointer>*>(m_shmem.get_user_address());
  637. //Check if buffer is smaller than maximum allowed
  638. if (buffer_size > p_hdr->m_max_msg_size) {
  639. throw interprocess_exception(size_error);
  640. }
  641. #if defined(BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX)
  642. bool notify_blocked_receivers = false;
  643. #endif
  644. //---------------------------------------------
  645. scoped_lock<interprocess_mutex> lock(p_hdr->m_mutex);
  646. //---------------------------------------------
  647. {
  648. //If the queue is full execute blocking logic
  649. if (p_hdr->is_full()) {
  650. BOOST_TRY{
  651. #ifdef BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX
  652. ++p_hdr->m_blocked_senders;
  653. #endif
  654. switch(block){
  655. case non_blocking :
  656. #ifdef BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX
  657. --p_hdr->m_blocked_senders;
  658. #endif
  659. return false;
  660. break;
  661. case blocking :
  662. do{
  663. p_hdr->m_cond_send.wait(lock);
  664. }
  665. while (p_hdr->is_full());
  666. break;
  667. case timed :
  668. do{
  669. if(!p_hdr->m_cond_send.timed_wait(lock, abs_time)){
  670. if(p_hdr->is_full()){
  671. #ifdef BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX
  672. --p_hdr->m_blocked_senders;
  673. #endif
  674. return false;
  675. }
  676. break;
  677. }
  678. }
  679. while (p_hdr->is_full());
  680. break;
  681. default:
  682. break;
  683. }
  684. #ifdef BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX
  685. --p_hdr->m_blocked_senders;
  686. #endif
  687. }
  688. BOOST_CATCH(...){
  689. #ifdef BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX
  690. --p_hdr->m_blocked_senders;
  691. #endif
  692. BOOST_RETHROW;
  693. }
  694. BOOST_CATCH_END
  695. }
  696. #if defined(BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX)
  697. notify_blocked_receivers = 0 != p_hdr->m_blocked_receivers;
  698. #endif
  699. //Insert the first free message in the priority queue
  700. ipcdetail::msg_hdr_t<VoidPointer> &free_msg_hdr = p_hdr->queue_free_msg(priority);
  701. //Sanity check, free msgs are always cleaned when received
  702. BOOST_ASSERT(free_msg_hdr.priority == 0);
  703. BOOST_ASSERT(free_msg_hdr.len == 0);
  704. //Copy control data to the free message
  705. free_msg_hdr.priority = priority;
  706. free_msg_hdr.len = buffer_size;
  707. //Copy user buffer to the message
  708. std::memcpy(free_msg_hdr.data(), buffer, buffer_size);
  709. } // Lock end
  710. //Notify outside lock to avoid contention. This might produce some
  711. //spurious wakeups, but it's usually far better than notifying inside.
  712. //If this message changes the queue empty state, notify it to receivers
  713. #if defined(BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX)
  714. if (notify_blocked_receivers){
  715. p_hdr->m_cond_recv.notify_one();
  716. }
  717. #else
  718. p_hdr->m_cond_recv.notify_one();
  719. #endif
  720. return true;
  721. }
  722. template<class VoidPointer>
  723. inline void message_queue_t<VoidPointer>::receive(void *buffer, size_type buffer_size,
  724. size_type &recvd_size, unsigned int &priority)
  725. { this->do_receive(blocking, buffer, buffer_size, recvd_size, priority, ptime()); }
  726. template<class VoidPointer>
  727. inline bool
  728. message_queue_t<VoidPointer>::try_receive(void *buffer, size_type buffer_size,
  729. size_type &recvd_size, unsigned int &priority)
  730. { return this->do_receive(non_blocking, buffer, buffer_size, recvd_size, priority, ptime()); }
  731. template<class VoidPointer>
  732. inline bool
  733. message_queue_t<VoidPointer>::timed_receive(void *buffer, size_type buffer_size,
  734. size_type &recvd_size, unsigned int &priority,
  735. const boost::posix_time::ptime &abs_time)
  736. {
  737. if(abs_time == boost::posix_time::pos_infin){
  738. this->receive(buffer, buffer_size, recvd_size, priority);
  739. return true;
  740. }
  741. return this->do_receive(timed, buffer, buffer_size, recvd_size, priority, abs_time);
  742. }
  743. template<class VoidPointer>
  744. inline bool
  745. message_queue_t<VoidPointer>::do_receive(block_t block,
  746. void *buffer, size_type buffer_size,
  747. size_type &recvd_size, unsigned int &priority,
  748. const boost::posix_time::ptime &abs_time)
  749. {
  750. ipcdetail::mq_hdr_t<VoidPointer> *p_hdr = static_cast<ipcdetail::mq_hdr_t<VoidPointer>*>(m_shmem.get_user_address());
  751. //Check if buffer is big enough for any message
  752. if (buffer_size < p_hdr->m_max_msg_size) {
  753. throw interprocess_exception(size_error);
  754. }
  755. #if defined(BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX)
  756. bool notify_blocked_senders = false;
  757. #endif
  758. //---------------------------------------------
  759. scoped_lock<interprocess_mutex> lock(p_hdr->m_mutex);
  760. //---------------------------------------------
  761. {
  762. //If there are no messages execute blocking logic
  763. if (p_hdr->is_empty()) {
  764. BOOST_TRY{
  765. #if defined(BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX)
  766. ++p_hdr->m_blocked_receivers;
  767. #endif
  768. switch(block){
  769. case non_blocking :
  770. #if defined(BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX)
  771. --p_hdr->m_blocked_receivers;
  772. #endif
  773. return false;
  774. break;
  775. case blocking :
  776. do{
  777. p_hdr->m_cond_recv.wait(lock);
  778. }
  779. while (p_hdr->is_empty());
  780. break;
  781. case timed :
  782. do{
  783. if(!p_hdr->m_cond_recv.timed_wait(lock, abs_time)){
  784. if(p_hdr->is_empty()){
  785. #if defined(BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX)
  786. --p_hdr->m_blocked_receivers;
  787. #endif
  788. return false;
  789. }
  790. break;
  791. }
  792. }
  793. while (p_hdr->is_empty());
  794. break;
  795. //Paranoia check
  796. default:
  797. break;
  798. }
  799. #if defined(BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX)
  800. --p_hdr->m_blocked_receivers;
  801. #endif
  802. }
  803. BOOST_CATCH(...){
  804. #if defined(BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX)
  805. --p_hdr->m_blocked_receivers;
  806. #endif
  807. BOOST_RETHROW;
  808. }
  809. BOOST_CATCH_END
  810. }
  811. #ifdef BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX
  812. notify_blocked_senders = 0 != p_hdr->m_blocked_senders;
  813. #endif
  814. //There is at least one message ready to pick, get the top one
  815. ipcdetail::msg_hdr_t<VoidPointer> &top_msg = p_hdr->top_msg();
  816. //Get data from the message
  817. recvd_size = top_msg.len;
  818. priority = top_msg.priority;
  819. //Some cleanup to ease debugging
  820. top_msg.len = 0;
  821. top_msg.priority = 0;
  822. //Copy data to receiver's bufers
  823. std::memcpy(buffer, top_msg.data(), recvd_size);
  824. //Free top message and put it in the free message list
  825. p_hdr->free_top_msg();
  826. } //Lock end
  827. //Notify outside lock to avoid contention. This might produce some
  828. //spurious wakeups, but it's usually far better than notifying inside.
  829. //If this reception changes the queue full state, notify senders
  830. #ifdef BOOST_INTERPROCESS_MSG_QUEUE_CIRCULAR_INDEX
  831. if (notify_blocked_senders){
  832. p_hdr->m_cond_send.notify_one();
  833. }
  834. #else
  835. p_hdr->m_cond_send.notify_one();
  836. #endif
  837. return true;
  838. }
  839. template<class VoidPointer>
  840. inline typename message_queue_t<VoidPointer>::size_type message_queue_t<VoidPointer>::get_max_msg() const
  841. {
  842. ipcdetail::mq_hdr_t<VoidPointer> *p_hdr = static_cast<ipcdetail::mq_hdr_t<VoidPointer>*>(m_shmem.get_user_address());
  843. return p_hdr ? p_hdr->m_max_num_msg : 0; }
  844. template<class VoidPointer>
  845. inline typename message_queue_t<VoidPointer>::size_type message_queue_t<VoidPointer>::get_max_msg_size() const
  846. {
  847. ipcdetail::mq_hdr_t<VoidPointer> *p_hdr = static_cast<ipcdetail::mq_hdr_t<VoidPointer>*>(m_shmem.get_user_address());
  848. return p_hdr ? p_hdr->m_max_msg_size : 0;
  849. }
  850. template<class VoidPointer>
  851. inline typename message_queue_t<VoidPointer>::size_type message_queue_t<VoidPointer>::get_num_msg() const
  852. {
  853. ipcdetail::mq_hdr_t<VoidPointer> *p_hdr = static_cast<ipcdetail::mq_hdr_t<VoidPointer>*>(m_shmem.get_user_address());
  854. if(p_hdr){
  855. //---------------------------------------------
  856. scoped_lock<interprocess_mutex> lock(p_hdr->m_mutex);
  857. //---------------------------------------------
  858. return p_hdr->m_cur_num_msg;
  859. }
  860. return 0;
  861. }
  862. template<class VoidPointer>
  863. inline bool message_queue_t<VoidPointer>::remove(const char *name)
  864. { return shared_memory_object::remove(name); }
  865. #else
  866. //!Typedef for a default message queue
  867. //!to be used between processes
  868. typedef message_queue_t<offset_ptr<void> > message_queue;
  869. #endif //#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED
  870. }} //namespace boost{ namespace interprocess{
  871. #include <boost/interprocess/detail/config_end.hpp>
  872. #endif //#ifndef BOOST_INTERPROCESS_MESSAGE_QUEUE_HPP