forked from zeromq/libzmq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmailbox_safe.cpp
98 lines (80 loc) · 2.5 KB
/
mailbox_safe.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* SPDX-License-Identifier: MPL-2.0 */
#include "precompiled.hpp"
#include "mailbox_safe.hpp"
#include "clock.hpp"
#include "err.hpp"
#include <algorithm>
zmq::mailbox_safe_t::mailbox_safe_t (mutex_t *sync_) : _sync (sync_)
{
// Get the pipe into passive state. That way, if the users starts by
// polling on the associated file descriptor it will get woken up when
// new command is posted.
const bool ok = _cpipe.check_read ();
zmq_assert (!ok);
}
zmq::mailbox_safe_t::~mailbox_safe_t ()
{
// TODO: Retrieve and deallocate commands inside the cpipe.
// Work around problem that other threads might still be in our
// send() method, by waiting on the mutex before disappearing.
_sync->lock ();
_sync->unlock ();
}
void zmq::mailbox_safe_t::add_signaler (signaler_t *signaler_)
{
_signalers.push_back (signaler_);
}
void zmq::mailbox_safe_t::remove_signaler (signaler_t *signaler_)
{
// TODO: make a copy of array and signal outside the lock
const std::vector<zmq::signaler_t *>::iterator end = _signalers.end ();
const std::vector<signaler_t *>::iterator it =
std::find (_signalers.begin (), end, signaler_);
if (it != end)
_signalers.erase (it);
}
void zmq::mailbox_safe_t::clear_signalers ()
{
_signalers.clear ();
}
void zmq::mailbox_safe_t::send (const command_t &cmd_)
{
_sync->lock ();
_cpipe.write (cmd_, false);
const bool ok = _cpipe.flush ();
if (!ok) {
_cond_var.broadcast ();
for (std::vector<signaler_t *>::iterator it = _signalers.begin (),
end = _signalers.end ();
it != end; ++it) {
(*it)->send ();
}
}
_sync->unlock ();
}
int zmq::mailbox_safe_t::recv (command_t *cmd_, int timeout_)
{
// Try to get the command straight away.
if (_cpipe.read (cmd_))
return 0;
// If the timeout is zero, it will be quicker to release the lock, giving other a chance to send a command
// and immediately relock it.
if (timeout_ == 0) {
_sync->unlock ();
_sync->lock ();
} else {
// Wait for signal from the command sender.
const int rc = _cond_var.wait (_sync, timeout_);
if (rc == -1) {
errno_assert (errno == EAGAIN || errno == EINTR);
return -1;
}
}
// Another thread may already fetch the command
const bool ok = _cpipe.read (cmd_);
if (!ok) {
errno = EAGAIN;
return -1;
}
return 0;
}