Skip to content

Commit

Permalink
[Xsocket] Fixed issue with infinite thread spawning (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
Gliniak authored Dec 24, 2023
1 parent ddf88c0 commit 7f981ef
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
24 changes: 17 additions & 7 deletions src/xenia/kernel/xsocket.cc
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
#include <unistd.h>
#endif

using namespace std::chrono_literals;

namespace xe {
namespace kernel {

Expand Down Expand Up @@ -173,8 +175,8 @@ X_STATUS XSocket::Bind(const XSOCKADDR* name, int name_len) {

auto addrin = reinterpret_cast<sockaddr_in*>(&n_name);

addrin->sin_port =
htons(XLiveAPI::upnp_handler.get_mapped_bind_port(ntohs(addrin->sin_port)));
addrin->sin_port = htons(
XLiveAPI::upnp_handler.get_mapped_bind_port(ntohs(addrin->sin_port)));

int ret = bind(native_handle_, (sockaddr*)&n_name, name_len);
if (ret < 0) {
Expand Down Expand Up @@ -499,9 +501,17 @@ int XSocket::WSARecvFrom(XWSABUF* buffers, uint32_t num_buffers,
xboxkrnl::xeNtClearEvent(overlapped_ptr->event_handle);
}
active_overlapped_ = overlapped_ptr;
receive_thread_ = std::thread(&XSocket::PollWSARecvFrom, this, true,
receive_async_data);
receive_thread_.detach();

if (!pooling_task_.valid()) {
pooling_task_ =
std::async(std::launch::async, &XSocket::PollWSARecvFrom, this,
true, receive_async_data);
} else {
auto status = pooling_task_.wait_for(0ms);
if (status == std::future_status::ready) {
auto result = pooling_task_.get();
}
}
SetLastWSAError(X_WSAError::X_WSA_IO_PENDING);
}

Expand Down Expand Up @@ -582,8 +592,8 @@ int XSocket::SendTo(uint8_t* buf, uint32_t buf_len, uint32_t flags,
}

auto addrin = reinterpret_cast<sockaddr_in*>(&nto);
addrin->sin_port =
htons(XLiveAPI::upnp_handler.get_mapped_bind_port(ntohs(addrin->sin_port)));
addrin->sin_port = htons(
XLiveAPI::upnp_handler.get_mapped_bind_port(ntohs(addrin->sin_port)));

return sendto(native_handle_, reinterpret_cast<char*>(buf), buf_len, flags,
to ? (const sockaddr*)&nto : nullptr, to_len);
Expand Down
4 changes: 3 additions & 1 deletion src/xenia/kernel/xsocket.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#define XENIA_KERNEL_XSOCKET_H_

#include <cstring>
#include <future>
#include <queue>

#include "xenia/base/byte_order.h"
Expand Down Expand Up @@ -148,7 +149,8 @@ class XSocket : public XObject {
std::mutex incoming_packet_mutex_;
std::queue<uint8_t*> incoming_packets_;

std::thread receive_thread_;
std::future<int> pooling_task_;

std::mutex receive_mutex_;
std::condition_variable receive_cv_;
std::mutex receive_socket_mutex_;
Expand Down

0 comments on commit 7f981ef

Please sign in to comment.