message_queue.hpp 36 KB

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