Skip to content

Commit 4dc4bcd

Browse files
authored
Wait for http request completion with condition variable (#1524)
1 parent 358c49a commit 4dc4bcd

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

include/dpp/queues.h

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
#include <vector>
3131
#include <functional>
3232
#include <atomic>
33+
#include <condition_variable>
3334
#include <dpp/httpsclient.h>
3435

3536
namespace dpp {
@@ -240,6 +241,22 @@ class DPP_EXPORT http_request {
240241
*/
241242
std::unique_ptr<https_client> cli;
242243

244+
/**
245+
* @brief Mutex for this_captured_signal and this_captured
246+
*/
247+
std::mutex this_captured_mutex;
248+
249+
/**
250+
* @brief Condition variable to signal this is no longer captured by an ongoing lambda
251+
*/
252+
std::condition_variable this_captured_signal;
253+
254+
255+
/**
256+
* @brief True if this is currently captured in a lambda and cannot be deleted
257+
*/
258+
bool this_captured{false};
259+
243260
public:
244261
/**
245262
* @brief Endpoint name

src/dpp/queues.cpp

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,10 @@ http_request::http_request(const std::string &_url, http_completion_event comple
107107
{
108108
}
109109

110-
http_request::~http_request() = default;
110+
http_request::~http_request() {
111+
std::unique_lock<std::mutex> lock(this_captured_mutex);
112+
this_captured_signal.wait(lock, [this] { return !this_captured; });
113+
}
111114

112115
void http_request::complete(const http_request_completion_t &c) {
113116
if (complete_handler) {
@@ -260,6 +263,10 @@ http_request_completion_t http_request::run(request_concurrency_queue* processor
260263
processor->buckets[this->endpoint] = newbucket;
261264

262265
/* Transfer it to completed requests */
266+
{
267+
std::lock_guard<std::mutex> lock(this_captured_mutex);
268+
this_captured = true;
269+
}
263270
owner->queue_work(0, [owner, this, result, hci, _url]() {
264271
try {
265272
complete(result);
@@ -271,6 +278,11 @@ http_request_completion_t http_request::run(request_concurrency_queue* processor
271278
owner->log(ll_error, "Uncaught exception thrown in HTTPS callback for " + std::string(request_verb[method]) + " " + hci.hostname + ":" + std::to_string(hci.port) + _url + ": <non exception value>");
272279
}
273280
completed = true;
281+
{
282+
std::lock_guard<std::mutex> lock(this_captured_mutex);
283+
this_captured = false;
284+
}
285+
this_captured_signal.notify_all();
274286
});
275287
}
276288
);

0 commit comments

Comments
 (0)