message_queue.hpp 36 KB

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