Skip to content
This repository was archived by the owner on Apr 6, 2019. It is now read-only.

Commit 67c61a4

Browse files
committed
#4 add is_notified atomic variable to avoid locking is conditional variable has already been notified
1 parent dc251c6 commit 67c61a4

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

sources/network/tcp_client.cpp

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,19 +29,24 @@ tcp_client::connect(const std::string& host, unsigned int port) {
2929
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(host), port);
3030

3131
//! async connect
32+
std::atomic_bool is_notified(false);
3233
m_socket.async_connect(endpoint, [&](boost::system::error_code error) {
3334
if (not error) {
3435
m_is_connected = true;
3536
async_read();
3637
}
38+
39+
is_notified = true;
3740
conn_cond_var.notify_one();
3841
});
3942

4043
//! start loop and wait for async connect result
4144
std::mutex conn_mutex;
4245
std::unique_lock<std::mutex> lock(conn_mutex);
4346
m_io_service.run();
44-
conn_cond_var.wait(lock);
47+
48+
if (not is_notified)
49+
conn_cond_var.wait(lock);
4550

4651
if (not m_is_connected)
4752
throw redis_error("Fail to connect to " + host + ":" + std::to_string(port));
@@ -58,12 +63,16 @@ tcp_client::disconnect(void) {
5863
std::condition_variable close_socket_cond_var;
5964
std::unique_lock<std::mutex> lock(close_socket_mutex);
6065

61-
m_io_service.post([this, &close_socket_cond_var]() {
66+
std::atomic_bool is_notified(false);
67+
m_io_service.post([this, &close_socket_cond_var, &is_notified]() {
6268
m_socket.close();
69+
70+
is_notified = true;
6371
close_socket_cond_var.notify_one();
6472
});
6573

66-
close_socket_cond_var.wait(lock);
74+
if (not is_notified)
75+
close_socket_cond_var.wait(lock);
6776
}
6877

6978
void

0 commit comments

Comments
 (0)