Skip to content

Commit 1e69ebc

Browse files
committed
optimize lock-wait by double-check.
1 parent ed71e22 commit 1e69ebc

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

src/transport/TcpTransport.cpp

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,10 @@ TcpConnectStatus TcpTransport::getTcpConnectStatus() {
6767
}
6868

6969
TcpConnectStatus TcpTransport::waitTcpConnectEvent(int timeoutMillis) {
70-
std::unique_lock<std::mutex> eventLock(m_connectEventLock);
7170
if (m_tcpConnectStatus == TCP_CONNECT_STATUS_WAIT) {
72-
if (m_connectEvent.wait_for(eventLock, std::chrono::milliseconds(timeoutMillis)) == std::cv_status::timeout) {
71+
std::unique_lock<std::mutex> eventLock(m_connectEventLock);
72+
if (!m_connectEvent.wait_for(eventLock, std::chrono::milliseconds(timeoutMillis),
73+
[&] { return m_tcpConnectStatus != TCP_CONNECT_STATUS_WAIT; })) {
7374
LOG_INFO("connect timeout");
7475
}
7576
}
@@ -80,7 +81,7 @@ TcpConnectStatus TcpTransport::waitTcpConnectEvent(int timeoutMillis) {
8081
void TcpTransport::setTcpConnectEvent(TcpConnectStatus connectStatus) {
8182
TcpConnectStatus baseStatus = m_tcpConnectStatus.exchange(connectStatus, std::memory_order_relaxed);
8283
if (baseStatus == TCP_CONNECT_STATUS_WAIT) {
83-
std::unique_lock<std::mutex> eventLock(m_connectEventLock);
84+
// awake waiting thread
8485
m_connectEvent.notify_all();
8586
}
8687
}

0 commit comments

Comments
 (0)