Skip to content

Commit 8cf1673

Browse files
committed
refactor(server): change conn->closed to atomic, try to fix possible data race
1 parent 79a82ec commit 8cf1673

3 files changed

Lines changed: 7 additions & 5 deletions

File tree

include/swoole_server.h

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,6 @@ struct Connection {
8787
uint8_t websocket_compression;
8888
// If it is equal to 1, it means server actively closed the connection
8989
uint8_t close_actively;
90-
uint8_t closed;
9190
uint8_t close_queued;
9291
uint8_t closing;
9392
uint8_t close_reset;
@@ -99,6 +98,7 @@ struct Connection {
9998
ReactorId reactor_id;
10099
uint16_t close_errno;
101100
int server_fd;
101+
sw_atomic_t closed;
102102
sw_atomic_t recv_queued_bytes;
103103
uint32_t send_queued_bytes;
104104
uint16_t waiting_time;
@@ -1308,6 +1308,10 @@ class Server {
13081308
return session->reactor_id != swoole_get_worker_id();
13091309
}
13101310

1311+
bool if_do_close_callback(Connection *conn) const {
1312+
return onClose != nullptr && sw_atomic_cmp_set(&conn->closed, 0, 1);
1313+
}
1314+
13111315
Worker *get_worker(uint16_t worker_id) const;
13121316
bool kill_worker(int worker_id);
13131317
void stop_async_worker(Worker *worker);

src/server/base.cc

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ bool BaseFactory::end(SessionId session_id, int flags) {
170170
}
171171

172172
conn->closing = 1;
173-
if (server_->onClose != nullptr && !conn->closed) {
173+
if (server_->if_do_close_callback(conn)) {
174174
DataHead info{};
175175
info.fd = session_id;
176176
if (conn->close_actively) {
@@ -182,7 +182,6 @@ bool BaseFactory::end(SessionId session_id, int flags) {
182182
server_->onClose(server_, &info);
183183
}
184184
conn->closing = 0;
185-
conn->closed = 1;
186185
conn->close_errno = 0;
187186
network::Socket *_socket = conn->socket;
188187

src/server/process.cc

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -415,7 +415,7 @@ bool ProcessFactory::end(SessionId session_id, int flags) {
415415
return false;
416416
}
417417

418-
if (server_->onClose != nullptr && !conn->closed) {
418+
if (server_->if_do_close_callback(conn)) {
419419
info.fd = session_id;
420420
if (conn->close_actively) {
421421
info.reactor_id = -1;
@@ -427,7 +427,6 @@ bool ProcessFactory::end(SessionId session_id, int flags) {
427427
server_->onClose(server_, &info);
428428
conn->closing = 0;
429429
}
430-
conn->closed = 1;
431430
conn->close_errno = 0;
432431
return finish(&_send);
433432
}

0 commit comments

Comments
 (0)