Skip to content

Commit

Permalink
Merge pull request #205 from edave64/shorter_sleep
Browse files Browse the repository at this point in the history
Use a condition_variable to abort waiting in the server scan thread
  • Loading branch information
daid authored Feb 21, 2022
2 parents 91b8a71 + 757967f commit d2aa22a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/multiplayer_server_scanner.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include "multiplayer_server_scanner.h"
#include "io/http/request.h"
using namespace std::chrono_literals;

ServerScanner::ServerScanner(int version_number, int server_port)
: server_port(server_port), version_number(version_number)
Expand All @@ -15,6 +16,7 @@ ServerScanner::~ServerScanner()

void ServerScanner::scanMasterServer(string url)
{
abort_wait.notify_all();
if (master_server_scan_thread.joinable())
return;
LOG(INFO) << "Switching to master server scanning";
Expand Down Expand Up @@ -45,6 +47,7 @@ void ServerScanner::scanLocalNetwork()

LOG(INFO) << "Switching to local server scanning";
master_server_url = "";
abort_wait.notify_all();
if (master_server_scan_thread.joinable())
{
master_server_scan_thread.join();
Expand Down Expand Up @@ -209,8 +212,16 @@ void ServerScanner::masterServerScanThread()
}
}
}

for(int n=0;n<10 && !isDestroyed() && master_server_url != ""; n++)
std::this_thread::sleep_for(std::chrono::duration<float>(1.f));

if (!isDestroyed() && master_server_url != "") {
std::mutex wait_mutex;
std::unique_lock<std::mutex> lk(wait_mutex);
abort_wait.wait_for(lk, 10s);
}
}
}

void ServerScanner::destroy() {
PObject::destroy();
abort_wait.notify_all();
}
4 changes: 4 additions & 0 deletions src/multiplayer_server_scanner.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include "multiplayer_server.h"
#include <thread>
#include <mutex>
#include <condition_variable>


//Class to find all servers that have the correct version number. Creates a big nice list.
Expand Down Expand Up @@ -32,6 +33,7 @@ class ServerScanner : public Updatable
string master_server_url;
std::mutex server_list_mutex;
std::thread master_server_scan_thread;
std::condition_variable abort_wait;

std::function<void(sp::io::network::Address, string)> newServerCallback;
std::function<void(sp::io::network::Address)> removedServerCallback;
Expand All @@ -40,6 +42,8 @@ class ServerScanner : public Updatable
ServerScanner(int version_number, int server_port = defaultServerPort);
virtual ~ServerScanner();

virtual void destroy() override;

virtual void update(float delta) override;
void addCallbacks(std::function<void(sp::io::network::Address, string)> newServerCallback, std::function<void(sp::io::network::Address)> removedServerCallback);

Expand Down

0 comments on commit d2aa22a

Please sign in to comment.