Moved the thread out of the NetworkQueue class

This commit is contained in:
Kayne Ruse
2013-11-09 20:04:06 +11:00
parent bf15a5d957
commit c2941cd3e8
4 changed files with 115 additions and 145 deletions
+10 -72
View File
@@ -1,71 +1,23 @@
#include "network_queue.hpp"
#include "utility.hpp"
#include <stdexcept>
#include <iostream>
int networkQueueThread(void* ptr) {
NetworkQueue* netQueue = reinterpret_cast<NetworkQueue*>(ptr);
NetworkPacket packet;
while(netQueue->running) {
SDL_SemWait(netQueue->lock);
//suck in the waiting packets
while(netQueue->netUtil->Receive()) {
memcpy(&packet, netQueue->netUtil->GetInData(), sizeof(NetworkPacket));
//this is important: keep track of the source address
packet.meta.srcAddress = netQueue->netUtil->GetInPacket()->address;
netQueue->queue.push_back(packet);
}
SDL_SemPost(netQueue->lock);
SDL_Delay(10);
}
return 0;
}
void NetworkQueue::Init(UDPNetworkUtility* ptr) {
if (running) {
throw(std::runtime_error("Network Queue is already running"));
}
running = true;
netUtil = ptr;
NetworkQueue::NetworkQueue() {
lock = SDL_CreateSemaphore(1);
thread = SDL_CreateThread(networkQueueThread, this);
if (!thread) {
throw(std::runtime_error("Failed to create the network thread"));
if (!lock) {
throw(std::runtime_error("Failed to create NetworkQueue::lock"));
}
}
void NetworkQueue::Quit() {
if (!running) {
return;
}
//end the thread
running = false;
int ret;
SDL_WaitThread(thread, &ret);
ResetMembers();
//handle the return
if (ret != 0) {
throw(std::runtime_error(std::string() + "Network thread returned error code: " + to_string_custom(ret)));
}
NetworkQueue::~NetworkQueue() {
SDL_DestroySemaphore(lock);
}
void NetworkQueue::Kill() {
if (!running) {
return;
}
running = false;
SDL_KillThread(thread);
ResetMembers();
NetworkPacket NetworkQueue::Push(NetworkPacket packet) {
SDL_SemWait(lock);
queue.push_back(packet);
SDL_SemPost(lock);
return packet;
}
NetworkPacket NetworkQueue::Peek() {
@@ -91,24 +43,10 @@ NetworkPacket NetworkQueue::Pop() {
void NetworkQueue::Flush() {
SDL_SemWait(lock);
while(netUtil->Receive());
queue.clear();
SDL_SemPost(lock);
}
void NetworkQueue::ResetMembers() {
if (running) {
throw(std::logic_error("Cannon reset the queue while running"));
}
//reset
netUtil = nullptr;
SDL_DestroySemaphore(lock);
lock = nullptr;
thread = nullptr;
queue.clear();
}
int NetworkQueue::Size() {
//can't be sure if std::deque::size() is thread safe
int ret;