Skip to content

Commit

Permalink
Ensure thread safety for Socket's deconstruction (#205)
Browse files Browse the repository at this point in the history
  • Loading branch information
baigao-X authored Jan 6, 2024
1 parent cbf37b1 commit 45d3570
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 10 deletions.
15 changes: 6 additions & 9 deletions src/Network/Socket.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,20 +49,17 @@ static SockException getSockErr(int sock, bool try_errno = true) {
return toSockException(error);
}

Socket::Ptr Socket::createSocket(const EventPoller::Ptr &poller, bool enable_mutex) {
return std::make_shared<Socket>(poller, enable_mutex);
Socket::Ptr Socket::createSocket(const EventPoller::Ptr &poller_in, bool enable_mutex) {
auto poller = poller_in ? poller_in : EventPollerPool::Instance().getPoller();
return Socket::Ptr(new Socket(poller, enable_mutex), [poller](Socket *ptr) { poller->async([ptr]() { delete ptr; }); });
}

Socket::Socket(const EventPoller::Ptr &poller, bool enable_mutex)
: _mtx_sock_fd(enable_mutex)
Socket::Socket(EventPoller::Ptr poller, bool enable_mutex)
: _poller(std::move(poller))
, _mtx_sock_fd(enable_mutex)
, _mtx_event(enable_mutex)
, _mtx_send_buf_waiting(enable_mutex)
, _mtx_send_buf_sending(enable_mutex) {

_poller = poller;
if (!_poller) {
_poller = EventPollerPool::Instance().getPoller();
}
setOnRead(nullptr);
setOnErr(nullptr);
setOnAccept(nullptr);
Expand Down
3 changes: 2 additions & 1 deletion src/Network/Socket.h
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,6 @@ class Socket : public std::enable_shared_from_this<Socket>, public noncopyable,
* @param enable_mutex 是否启用互斥锁(接口是否线程安全)
*/
static Ptr createSocket(const EventPoller::Ptr &poller = nullptr, bool enable_mutex = true);
Socket(const EventPoller::Ptr &poller = nullptr, bool enable_mutex = true);
~Socket() override;

/**
Expand Down Expand Up @@ -512,6 +511,8 @@ class Socket : public std::enable_shared_from_this<Socket>, public noncopyable,
std::string getIdentifier() const override;

private:
Socket(EventPoller::Ptr poller, bool enable_mutex = true);

void setSock(SockNum::Ptr sock);
int onAccept(const SockNum::Ptr &sock, int event) noexcept;
ssize_t onRead(const SockNum::Ptr &sock, const BufferRaw::Ptr &buffer) noexcept;
Expand Down

0 comments on commit 45d3570

Please sign in to comment.