![]() |
![]() ![]() ![]() ![]() ![]() |
![]() |
Class reliable_message_queueBoost , Chapter 1. Boost.Log v2 , Utilities
|
Постусловия: |
|
Конструктор. Метод используется для построения объекта и создания соответствующей очереди сообщений. Построенный объект будет в рабочем состоянии, если очередь сообщения будет успешно создана.
Параметры: |
| ||||||||||
Почтовые условия: |
|
Constructor. The method is used to construct an object and create the associated message queue. The constructed object will be in running state if the message queue is successfully created.
Parameters: |
| ||||||||||
Постусловия: |
|
reliable_message_queue(open_mode::open_or_create_tag, object_name const & name, uint32_t capacity, size_type block_size, overflow_policy oflow_policy = block_on_overflow, permissions const & perms = permissions());
Constructor. The method is used to construct an object and create or open the associated message queue. The constructed object will be in running state if the message queue is successfully created or opened. If the message queue that is identified by the name already exists then the other queue parameters are ignored. The actual queue parameters can be obtained with accessors from the constructed object.
Parameters: |
| ||||||||||
Постусловия: |
|
Конструктор. Метод используется для построения объекта и открытия существующей очереди сообщений. Построенный объект будет в рабочем состоянии, если очередь сообщения будет успешно открыта.
Параметры: |
| ||||||
Почтовые условия: |
|
Constructor. The method is used to construct an object and open the existing message queue. The constructed object will be in running state if the message queue is successfully opened.
Parameters: |
| ||||||
Постусловия: |
|
template<typename... Args> explicit reliable_message_queue(Args const &... args);
Constructor with named parameters. The method is used to construct an object and create or open the associated message queue. The constructed object will be in running state if the message queue is successfully created.
The following named parameters are accepted:
open_mode - One of the open mode tags: open_mode::create_only
, open_mode::open_only
or open_mode::open_or_create
.
Имя - Имя очереди сообщений, с которой следует ассоциироваться.
емкость - максимальное количество блоков распределения, которые может удерживать очередь. Используется только при создании очереди.
block_size - Размер в байтах блока распределения. Это должна быть сила 2. Используется только при создании очереди.
overflow_policy - Политика поведения в случае переполнения см. overflow_policy
.
Разрешения - Разрешения доступа для соответствующей очереди сообщений.
Постусловия: |
|
Составник. Метод перемещает объект из other
. После вызова построенный объект становится other
, а other
остается в по умолчанию построенном состоянии.
Параметры: |
|
Move constructor. The method move-constructs an object from other
. After the call, the constructed object becomes other
, while other
is left in default constructed state.
Parameters: |
|
reliable_message_queue & operator=(reliable_message_queue && that) noexcept;
Move assignment operator. If the object is associated with a message queue, close()
is first called and the precondition to calling close()
applies. After the call, the object becomes that while that is left in default constructed state.
Parameters: |
| ||
Returns: | A reference to the assigned object. |
~reliable_message_queue();
Destructor. Calls close()
.
reliable_message_queue
public member functionsvoid swap(reliable_message_queue & that) noexcept;
The method swaps the object with that.
Parameters: |
|
void create(object_name const & name, uint32_t capacity, size_type block_size, overflow_policy oflow_policy = block_on_overflow, permissions const & perms = permissions());
The method creates the message queue to be associated with the object. After the call, the object will be in running state if a message queue is successfully created.
Parameters: |
| ||||||||||
Requires: |
| ||||||||||
Постусловия: |
|
void open_or_create(object_name const & name, uint32_t capacity, size_type block_size, overflow_policy oflow_policy = block_on_overflow, permissions const & perms = permissions());
The method creates or opens the message queue to be associated with the object. After the call, the object will be in running state if a message queue is successfully created or opened. If the message queue that is identified by the name already exists then the other queue parameters are ignored. The actual queue parameters can be obtained with accessors from this object after this method returns.
Parameters: |
| ||||||||||
Requires: |
| ||||||||||
Постусловия: |
|
Метод открывает существующую очередь сообщения для связи с объектом. После вызова объект будет в запущенном состоянии, если очередь сообщения будет успешно открыта.
Параметры: |
| ||||||
Требования: |
| ||||||
Почтовые условия: |
|
The method opens the existing message queue to be associated with the object. After the call, the object will be in running state if a message queue is successfully opened.
Parameters: |
| ||||||
Requires: |
| ||||||
Постусловия: |
|
bool is_open() const noexcept;
Tests whether the object is associated with any message queue.
Returns: |
|
Этот метод освобождает связанную очередь сообщения. Разрешены одновременные звонки на этот метод, send()
, try_send()
, receive()
, try_receive()
и stop_local()
.
Требования: |
This method empties the associated message queue. Concurrent calls to this method, send()
, try_send()
, receive()
, try_receive()
, and stop_local()
are allowed.
Requires: |
|
object_name const & name() const;
The method returns the name of the associated message queue.
Requires: |
|
Returns: | Name of the associated message queue |
uint32_t capacity() const;
The method returns the maximum number of allocation blocks the associated message queue can hold. Note that the returned value may be different from the corresponding value passed to the constructor or open_or_create()
, for the message queue may not have been created by this object.
Requires: |
|
Returns: | Maximum number of allocation blocks the associated message queue can hold. |
size_type block_size() const;
The method returns the allocation block size, in bytes. Each message in the associated message queue consumes an integer number of allocation blocks. Note that the returned value may be different from the corresponding value passed to the constructor or open_or_create()
, for the message queue may not have been created by this object.
Requires: |
|
Returns: | Allocation block size, in bytes. |
Метод пробуждает все нити, которые блокируются в вызовах send()
или receive()
. Эти звонки затем возвращают false
с errno
EINTR
. Обратите внимание, что метод не блокируется до тех пор, пока разбуденные нити не вернулись из send()
или receive()
. Необходимы другие средства для обеспечения того, чтобы звонки на send()
или receive()
вернулись, например, присоединяясь к потокам, которые могут блокировать звонки.
Также метод помещает объект в остановленное состояние. Когда в остановленном состоянии, звонки в send()
или receive()
сразу же вернутся с возвратным значением false
и errno
EINTR
, когда они в противном случае блокируют в рабочем состоянии.
Разрешены постоянные звонки на этот метод, send()
, try_send()
, receive()
, try_receive()
и clear()
.
Требования: |
The method wakes up all threads that are blocked in calls to send()
or receive()
. Those calls would then return false
with errno
EINTR
. Note that, the method does not block until the woken-up threads have actually returned from send()
or receive()
. Other means is needed to ensure that calls to send()
or receive()
have returned, e.g., joining the threads that might be blocking on the calls.
The method also puts the object in stopped state. When in stopped state, calls to send()
or receive()
will return immediately with return value false
and errno
EINTR
when they would otherwise block in running state.
Concurrent calls to this method, send()
, try_send()
, receive()
, try_receive()
, and clear()
are allowed.
Requires: |
|
void reset_local();
The method puts the object in running state where calls to send()
or receive()
may block. This method is not thread-safe.
Requires: |
|
Метод рассеивает связанную очередь сообщения, если таковая имеется. Никакие другие нити не должны использовать этот объект, прежде чем называть этот метод. Метод stop_local()
может быть использован, чтобы иметь любые потоки, которые в настоящее время заблокированы в возврате send()
или receive()
, и предотвратить дальнейшие звонки к ним от блокировки. Обычно, прежде чем называть этот метод, сначала позвоните stop_local()
, а затем присоединяйтесь ко всем потокам, которые могут блокировать send()
или receive()
, чтобы убедиться, что они вернулись с вызовов. Связанная очередь сообщения разрушается, если объект представляет последнюю выдающуюся ссылку на него.
Почтовые условия: |
|
The method disassociates the associated message queue, if any. No other threads should be using this object before calling this method. The stop_local()
method can be used to have any threads currently blocked in send()
or receive()
return, and prevent further calls to them from blocking. Typically, before calling this method, one would first call stop_local()
and then join all threads that might be blocking on send()
or receive()
to ensure that they have returned from the calls. The associated message queue is destroyed if the object represents the last outstanding reference to it.
Постусловия: |
|
Метод посылает сообщение в очередь сообщения. Когда объект находится в запущенном состоянии и очередь не имеет свободного места для сообщения, метод либо блокирует, либо бросает исключение, в зависимости от политики переполнения, которая была указана на открытии/создании очереди. Если политика блокировки действует, блокировка может быть прервана вызовом stop_local()
, в этом случае метод возвращает operation_result::aborted
. Когда объект уже находится в остановленном состоянии, метод не блокирует, а возвращает сразу с возвратным значением operation_result::aborted
.
Можно отправить пустое сообщение, передав 0
параметру message_size
.
Разрешены одновременные звонки на send()
, try_send()
, receive()
, try_receive()
, stop_local()
и clear()
.
Throws: std::logic_error
в случае, если размер сообщения превышает пропускную способность очереди, system_error
в случае, если уроженческий метод ОС не работает.
Параметры: |
| ||||
Требования: |
|
The method sends a message to the associated message queue. When the object is in running state and the queue has no free space for the message, the method either blocks or throws an exception, depending on the overflow policy that was specified on the queue opening/creation. If blocking policy is in effect, the blocking can be interrupted by calling stop_local()
, in which case the method returns operation_result::aborted
. When the object is already in the stopped state, the method does not block but returns immediately with return value operation_result::aborted
.
It is possible to send an empty message by passing 0
to the parameter message_size
.
Concurrent calls to send()
, try_send()
, receive()
, try_receive()
, stop_local()
, and clear()
are allowed.
Throws: std::logic_error
in case if the message size exceeds the queue capacity, system_error
in case if a native OS method fails.
Parameters: |
| ||||
Requires: |
|
bool try_send(void const * message_data, size_type message_size);
The method performs an attempt to send a message to the associated message queue. The method is non-blocking, and always returns immediately. boost::system::system_error
is thrown for errors resulting from native operating system calls. Note that it is possible to send an empty message by passing 0
to the parameter message_size
. Concurrent calls to send()
, try_send()
, receive()
, try_receive()
, stop_local()
, and clear()
are allowed.
Throws: std::logic_error
in case if the message size exceeds the queue capacity, system_error
in case if a native OS method fails.
Parameters: |
| ||||
Requires: |
| ||||
Returns: |
|
operation_result receive(void * buffer, size_type buffer_size, size_type & message_size);
The method takes a message from the associated message queue. When the object is in running state and the queue is empty, the method blocks. The blocking is interrupted when stop_local()
is called, in which case the method returns operation_result::aborted
. When the object is already in the stopped state and the queue is empty, the method does not block but returns immediately with return value operation_result::aborted
.
Concurrent calls to send()
, try_send()
, receive()
, try_receive()
, stop_local()
, and clear()
are allowed.
Parameters: |
| ||||||
Requires: |
|
template<typename ElementT, size_type SizeV> operation_result receive(ElementT(&) buffer, size_type & message_size);
The method takes a message from the associated message queue. When the object is in running state and the queue is empty, the method blocks. The blocking is interrupted when stop_local()
is called, in which case the method returns operation_result::aborted
. When the object is already in the stopped state and the queue is empty, the method does not block but returns immediately with return value operation_result::aborted
.
Concurrent calls to send()
, try_send()
, receive()
, try_receive()
, stop_local()
, and clear()
are allowed.
Parameters: |
| ||||
Requires: |
|
Метод принимает сообщение из соответствующей очереди сообщений. Когда объект находится в рабочем состоянии и очередь пуста, метод блокирует. Блокировка прерывается, когда называется stop_local()
, в этом случае метод возвращается operation_result::aborted
. Когда объект уже находится в остановленном состоянии и очередь пуста, метод не блокирует, а возвращает сразу с возвратным значением operation_result::aborted
.
Разрешены одновременные звонки на send()
, try_send()
, receive()
, try_receive()
, stop_local()
и clear()
.
Параметры: |
| ||
Требования: |
|
The method takes a message from the associated message queue. When the object is in running state and the queue is empty, the method blocks. The blocking is interrupted when stop_local()
is called, in which case the method returns operation_result::aborted
. When the object is already in the stopped state and the queue is empty, the method does not block but returns immediately with return value operation_result::aborted
.
Concurrent calls to send()
, try_send()
, receive()
, try_receive()
, stop_local()
, and clear()
are allowed.
Parameters: |
| ||
Requires: |
|
Метод выполняет попытку взять сообщение из соответствующей очереди сообщений. Метод не блокирует, и всегда возвращается сразу.
Разрешены одновременные звонки на send()
, try_send()
, receive()
, try_receive()
, stop_local()
и clear()
.
Параметры: |
| ||||||
Требования: |
| ||||||
Возвращение: |
|
The method performs an attempt to take a message from the associated message queue. The method is non-blocking, and always returns immediately.
Concurrent calls to send()
, try_send()
, receive()
, try_receive()
, stop_local()
, and clear()
are allowed.
Parameters: |
| ||||||
Requires: |
| ||||||
Returns: |
|
Метод выполняет попытку взять сообщение из соответствующей очереди сообщений. Метод не блокирует, и всегда возвращается сразу.
Разрешены одновременные звонки на send()
, try_send()
, receive()
, try_receive()
, stop_local()
и clear()
.
Параметры: |
| ||||
Требования: |
| ||||
Возвращение: |
|
The method performs an attempt to take a message from the associated message queue. The method is non-blocking, and always returns immediately.
Concurrent calls to send()
, try_send()
, receive()
, try_receive()
, stop_local()
, and clear()
are allowed.
Parameters: |
| ||||
Requires: |
| ||||
Returns: |
|
template<typename ContainerT> bool try_receive(ContainerT & container);
The method performs an attempt to take a message from the associated message queue. The method is non-blocking, and always returns immediately.
Concurrent calls to send()
, try_send()
, receive()
, try_receive()
, stop_local()
, and clear()
are allowed.
Parameters: |
| ||
Requires: |
| ||
Returns: |
|
reliable_message_queue
friend functionsfriend void swap(reliable_message_queue & a, reliable_message_queue & b) noexcept;Swaps the two
reliable_message_queue
objects. reliable_message_queue
public static functionsМетод освобождает общесистемные ресурсы, связанные с очередей межпроцессов с поставленным именем. Очередь, указанная указанным именем, не должна открываться в любом процессе в точке этого звонка. После этого вызова удается создать новую очередь с указанным именем.
Этот звонок может быть полезным для восстановления от более раннего процесса неправильного поведения (например, крушение без надлежащего закрытия очереди сообщения). В этом случае ресурсы, выделенные для межпроцессной очереди, могут оставаться выделенными после того, как последний процесс закрыл очередь, что, в свою очередь, может помешать созданию новой очереди с таким же названием. Позвонив этому методу перед созданием очереди, приложение может попытаться обеспечить его запуск с чистого листа.
На некоторых платформах ресурсы, связанные с очередей, автоматически воспроизводятся операционной системой, когда последний процесс использования этих ресурсов заканчивается (даже если он заканчивается аномально). На этих платформах этот вызов может быть безымянным. Тем не менее, переносной код должен по-прежнему называть этот метод в соответствующих местах, чтобы обеспечить совместимость с другими платформами и будущими версиями библиотеки, что может изменить реализацию очереди.
Параметры: |
|
The method frees system-wide resources, associated with the interprocess queue with the supplied name. The queue referred to by the specified name must not be opened in any process at the point of this call. After this call succeeds a new queue with the specified name can be created.
This call can be useful to recover from an earlier process misbehavior (e.g. a crash without properly closing the message queue). In this case resources allocated for the interprocess queue may remain allocated after the last process closed the queue, which in turn may prevent creating a new queue with the same name. By calling this method before creating a queue the application can attempt to ensure it starts with a clean slate.
On some platforms resources associated with the queue are automatically reclaimed by the operating system when the last process using those resources terminates (even if it terminates abnormally). On these platforms this call may be a no-op. However, portable code should still call this method at appropriate places to ensure compatibility with other platforms and future library versions, which may change implementation of the queue.
Parameters: |
|
Статья Class reliable_message_queue раздела Chapter 1. Boost.Log v2 Utilities может быть полезна для разработчиков на c++ и boost.
Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.
реклама |