Debian Codegraph @

cpp/examples/multithreaded_client_flow_control.cpp

raw
1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 //
21 // C++11 or greater
22 //
23 // A multi-threaded client that sends and receives messages from multiple AMQP
24 // addresses.
25 //
26 // Demonstrates how to:
27 //
28 // - implement proton handlers that interact with user threads safely
29 // - block sender threads to respect AMQP flow control
30 // - use AMQP flow control to limit message buffering for receivers threads
31 //
32 // We define sender and receiver classes with simple, thread-safe blocking
33 // send() and receive() functions.
34 //
35 // These classes are also privately proton::message_handler instances. They use
36 // the thread-safe proton::work_queue and standard C++ synchronization (std::mutex
37 // etc.) to pass messages between user and proton::container threads.
38 //
39 // NOTE: no proper error handling
40
41 #include <proton/connection.hpp>
42 #include <proton/connection_options.hpp>
43 #include <proton/container.hpp>
44 #include <proton/message.hpp>
45 #include <proton/messaging_handler.hpp>
46 #include <proton/receiver.hpp>
47 #include <proton/receiver_options.hpp>
48 #include <proton/sender.hpp>
49 #include <proton/work_queue.hpp>
50
51 #include <atomic>
52 #include <condition_variable>
53 #include <iostream>
54 #include <mutex>
55 #include <queue>
56 #include <sstream>
57 #include <string>
58 #include <thread>
59
60 // Lock output from threads to avoid scrambling
61 std::mutex out_lock;
62 #define OUT(x) do { std::lock_guard<std::mutex> l(out_lock); x; } while (false)
63
64 // Exception raised if a sender or receiver is closed when trying to send/receive
65 class closed : public std::runtime_error {
66 public:
67 closed(const std::string& msg) : std::runtime_error(msg) {}
68 };
69
70 // A thread-safe sending connection that blocks sending threads when there
71 // is no AMQP credit to send messages.
72 class sender : private proton::messaging_handler {
73 // Only used in proton handler thread
74 proton::sender sender_;
75
76 // Shared by proton and user threads, protected by lock_
77 std::mutex lock_;
78 proton::work_queue *work_queue_;
79 std::condition_variable sender_ready_;
80 int queued_; // Queued messages waiting to be sent
81 int credit_; // AMQP credit - number of messages we can send
82
83 public:
84 sender(proton::container& cont, const std::string& url, const std::string& address)
85 : work_queue_(0), queued_(0), credit_(0)
86 {
87 cont.open_sender(url+"/"+address, proton::connection_options().handler(*this));
88 }
89
90 // Thread safe
91 void send(const proton::message& m) {
92 {
93 std::unique_lock<std::mutex> l(lock_);
94 // Don't queue up more messages than we have credit for
95 while (!work_queue_ || queued_ >= credit_) sender_ready_.wait(l);
96 ++queued_;
97 }
98 work_queue_->add([=]() { this->do_send(m); }); // work_queue_ is thread safe
99 }
100
101 // Thread safe
102 void close() {
103 work_queue()->add([=]() { sender_.connection().close(); });
104 }
105
106 private:
107
108 proton::work_queue* work_queue() {
109 // Wait till work_queue_ and sender_ are initialized.
110 std::unique_lock<std::mutex> l(lock_);
111 while (!work_queue_) sender_ready_.wait(l);
112 return work_queue_;
113 }
114
115 // == messaging_handler overrides, only called in proton handler thread
116
117 void on_sender_open(proton::sender& s) override {
118 // Make sure sender_ and work_queue_ are set atomically
119 std::lock_guard<std::mutex> l(lock_);
120 sender_ = s;
121 work_queue_ = &s.work_queue();
122 }
123
124 void on_sendable(proton::sender& s) override {
125 std::lock_guard<std::mutex> l(lock_);
126 credit_ = s.credit();
127 sender_ready_.notify_all(); // Notify senders we have credit
128 }
129
130 // work_queue work items is are automatically dequeued and called by proton
131 // This function is called because it was queued by send()
132 void do_send(const proton::message& m) {
133 sender_.send(m);
134 std::lock_guard<std::mutex> l(lock_);
135 --queued_; // work item was consumed from the work_queue
136 credit_ = sender_.credit(); // update credit
137 sender_ready_.notify_all(); // Notify senders we have space on queue
138 }
139
140 void on_error(const proton::error_condition& e) override {
141 OUT(std::cerr << "unexpected error: " << e << std::endl);
142 exit(1);
143 }
144 };
145
146 // A thread safe receiving connection that blocks receiving threads when there
147 // are no messages available, and maintains a bounded buffer of incoming
148 // messages by issuing AMQP credit only when there is space in the buffer.
149 class receiver : private proton::messaging_handler {
150 static const size_t MAX_BUFFER = 100; // Max number of buffered messages
151
152 // Used in proton threads only
153 proton::receiver receiver_;
154
155 // Used in proton and user threads, protected by lock_
156 std::mutex lock_;
157 proton::work_queue* work_queue_;
158 std::queue<proton::message> buffer_; // Messages not yet returned by receive()
159 std::condition_variable can_receive_; // Notify receivers of messages
160 bool closed_;
161
162 public:
163
164 // Connect to url
165 receiver(proton::container& cont, const std::string& url, const std::string& address)
166 : work_queue_(0), closed_(false)
167 {
168 // NOTE:credit_window(0) disables automatic flow control.
169 // We will use flow control to match AMQP credit to buffer capacity.
170 cont.open_receiver(url+"/"+address, proton::receiver_options().credit_window(0),
171 proton::connection_options().handler(*this));
172 }
173
174 // Thread safe receive
175 proton::message receive() {
176 std::unique_lock<std::mutex> l(lock_);
177 // Wait for buffered messages
178 while (!closed_ && (!work_queue_ || buffer_.empty())) {
179 can_receive_.wait(l);
180 }
181 if (closed_) throw closed("receiver closed");
182 proton::message m = std::move(buffer_.front());
183 buffer_.pop();
184 // Add a lambda to the work queue to call receive_done().
185 // This will tell the handler to add more credit.
186 work_queue_->add([=]() { this->receive_done(); });
187 return m;
188 }
189
190 // Thread safe
191 void close() {
192 std::lock_guard<std::mutex> l(lock_);
193 if (!closed_) {
194 closed_ = true;
195 can_receive_.notify_all();
196 if (work_queue_) {
197 work_queue_->add([this]() { this->receiver_.connection().close(); });
198 }
199 }
200 }
201
202 private:
203 // ==== The following are called by proton threads only.
204
205 void on_receiver_open(proton::receiver& r) override {
206 receiver_ = r;
207 std::lock_guard<std::mutex> l(lock_);
208 work_queue_ = &receiver_.work_queue();
209 receiver_.add_credit(MAX_BUFFER); // Buffer is empty, initial credit is the limit
210 }
211
212 void on_message(proton::delivery &d, proton::message &m) override {
213 // Proton automatically reduces credit by 1 before calling on_message
214 std::lock_guard<std::mutex> l(lock_);
215 buffer_.push(m);
216 can_receive_.notify_all();
217 }
218
219 // called via work_queue
220 void receive_done() {
221 // Add 1 credit, a receiver has taken a message out of the buffer.
222 receiver_.add_credit(1);
223 }
224
225 void on_error(const proton::error_condition& e) override {
226 OUT(std::cerr << "unexpected error: " << e << std::endl);
227 exit(1);
228 }
229 };
230
231 // ==== Example code using the sender and receiver
232
233 // Send n messages
234 void send_thread(sender& s, int n) {
235 auto id = std::this_thread::get_id();
236 for (int i = 0; i < n; ++i) {
237 std::ostringstream ss;
238 ss << std::this_thread::get_id() << "-" << i;
239 s.send(proton::message(ss.str()));
240 OUT(std::cout << id << " sent \"" << ss.str() << '"' << std::endl);
241 }
242 OUT(std::cout << id << " sent " << n << std::endl);
243 }
244
245 // Receive messages till atomic remaining count is 0.
246 // remaining is shared among all receiving threads
247 void receive_thread(receiver& r, std::atomic_int& remaining) {
248 try {
249 auto id = std::this_thread::get_id();
250 int n = 0;
251 // atomically check and decrement remaining *before* receiving.
252 // If it is 0 or less then return, as there are no more
253 // messages to receive so calling r.receive() would block forever.
254 while (remaining-- > 0) {
255 auto m = r.receive();
256 ++n;
257 OUT(std::cout << id << " received \"" << m.body() << '"' << std::endl);
258 }
259 OUT(std::cout << id << " received " << n << " messages" << std::endl);
260 } catch (const closed&) {}
261 }
262
263 int main(int argc, const char **argv) {
264 try {
265 if (argc != 5) {
266 std::cerr <<
267 "Usage: " << argv[0] << " CONNECTION-URL AMQP-ADDRESS MESSAGE-COUNT THREAD-COUNT\n"
268 "CONNECTION-URL: connection address, e.g.'amqp://127.0.0.1'\n"
269 "AMQP-ADDRESS: AMQP node address, e.g. 'examples'\n"
270 "MESSAGE-COUNT: number of messages to send\n"
271 "THREAD-COUNT: number of sender/receiver thread pairs\n";
272 return 1;
273 }
274
275 const char *url = argv[1];
276 const char *address = argv[2];
277 int n_messages = atoi(argv[3]);
278 int n_threads = atoi(argv[4]);
279 int count = n_messages * n_threads;
280
281 // Total messages to be received, multiple receiver threads will decrement this.
282 std::atomic_int remaining;
283 remaining.store(count);
284
285 // Run the proton container
286 proton::container container;
287 auto container_thread = std::thread([&]() { container.run(); });
288
289 // A single sender and receiver to be shared by all the threads
290 sender send(container, url, address);
291 receiver recv(container, url, address);
292
293 // Start receiver threads, then sender threads.
294 // Starting receivers first gives all receivers a chance to compete for messages.
295 std::vector<std::thread> threads;
296 threads.reserve(n_threads*2); // Avoid re-allocation once threads are started
297 for (int i = 0; i < n_threads; ++i)
298 threads.push_back(std::thread([&]() { receive_thread(recv, remaining); }));
299 for (int i = 0; i < n_threads; ++i)
300 threads.push_back(std::thread([&]() { send_thread(send, n_messages); }));
301
302 // Wait for threads to finish
303 for (auto& t : threads) t.join();
304 send.close();
305 recv.close();
306 container_thread.join();
307 if (remaining > 0)
308 throw std::runtime_error("not all messages were received");
309 std::cout << count << " messages sent and received" << std::endl;
310
311 return 0;
312 } catch (const std::exception& e) {
313 std::cerr << e.what() << std::endl;
314 }
315 return 1;
316 }