From fb823dbca88b35cc7108d8311dca9f78a7f96f16 Mon Sep 17 00:00:00 2001 From: Hanif Bin Ariffin Date: Thu, 15 Oct 2020 08:51:09 +0800 Subject: [PATCH] 2 separate atomic RW operations are not atomic. Changed it to use CAS instead. Signed-off-by: Hanif Bin Ariffin --- src/connection.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/connection.cpp b/src/connection.cpp index bb3106a7e..877ed4c20 100644 --- a/src/connection.cpp +++ b/src/connection.cpp @@ -189,8 +189,11 @@ static int connSocketRead(connection *conn, void *buf, size_t buf_len) { static int connSocketAccept(connection *conn, ConnectionCallbackFunc accept_handler) { int ret = C_OK; - if (conn->state != CONN_STATE_ACCEPTING) return C_ERR; - conn->state = CONN_STATE_CONNECTED; + auto expected = CONN_STATE_ACCEPTING; + bool accepting = conn->state.compare_exchange_strong( + expected, CONN_STATE_CONNECTED, + std::memory_order_release, std::memory_order_relaxed); + if (!accepting) return C_ERR; connIncrRefs(conn); if (!callHandler(conn, accept_handler)) ret = C_ERR;