summaryrefslogtreecommitdiffstats
path: root/src/OSSupport
diff options
context:
space:
mode:
Diffstat (limited to 'src/OSSupport')
-rw-r--r--src/OSSupport/CMakeLists.txt10
-rw-r--r--src/OSSupport/CriticalSection.cpp52
-rw-r--r--src/OSSupport/CriticalSection.h14
-rw-r--r--src/OSSupport/Event.cpp156
-rw-r--r--src/OSSupport/Event.h35
-rw-r--r--src/OSSupport/IsThread.cpp174
-rw-r--r--src/OSSupport/IsThread.h51
-rw-r--r--src/OSSupport/Queue.h23
-rw-r--r--src/OSSupport/Sleep.cpp19
-rw-r--r--src/OSSupport/Sleep.h7
-rw-r--r--src/OSSupport/Socket.h2
-rw-r--r--src/OSSupport/SocketThreads.cpp14
-rw-r--r--src/OSSupport/StackTrace.cpp44
-rw-r--r--src/OSSupport/StackTrace.h15
-rw-r--r--src/OSSupport/Thread.cpp137
-rw-r--r--src/OSSupport/Thread.h26
-rw-r--r--src/OSSupport/Timer.cpp37
-rw-r--r--src/OSSupport/Timer.h32
18 files changed, 225 insertions, 623 deletions
diff --git a/src/OSSupport/CMakeLists.txt b/src/OSSupport/CMakeLists.txt
index c3eabeef6..e943ceb18 100644
--- a/src/OSSupport/CMakeLists.txt
+++ b/src/OSSupport/CMakeLists.txt
@@ -13,11 +13,10 @@ SET (SRCS
IsThread.cpp
ListenThread.cpp
Semaphore.cpp
- Sleep.cpp
Socket.cpp
SocketThreads.cpp
- Thread.cpp
- Timer.cpp)
+ StackTrace.cpp
+)
SET (HDRS
CriticalSection.h
@@ -29,11 +28,10 @@ SET (HDRS
ListenThread.h
Queue.h
Semaphore.h
- Sleep.h
Socket.h
SocketThreads.h
- Thread.h
- Timer.h)
+ StackTrace.h
+)
if(NOT MSVC)
add_library(OSSupport ${SRCS} ${HDRS})
diff --git a/src/OSSupport/CriticalSection.cpp b/src/OSSupport/CriticalSection.cpp
index 5dfc8b5f9..13a3e4d9f 100644
--- a/src/OSSupport/CriticalSection.cpp
+++ b/src/OSSupport/CriticalSection.cpp
@@ -1,6 +1,5 @@
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
-#include "IsThread.h"
@@ -9,41 +8,12 @@
////////////////////////////////////////////////////////////////////////////////
// cCriticalSection:
+#ifdef _DEBUG
cCriticalSection::cCriticalSection()
{
- #ifdef _WIN32
- InitializeCriticalSection(&m_CriticalSection);
- #else
- pthread_mutexattr_init(&m_Attributes);
- pthread_mutexattr_settype(&m_Attributes, PTHREAD_MUTEX_RECURSIVE);
-
- if (pthread_mutex_init(&m_CriticalSection, &m_Attributes) != 0)
- {
- LOGERROR("Could not initialize Critical Section!");
- }
- #endif
-
- #ifdef _DEBUG
- m_IsLocked = 0;
- #endif // _DEBUG
-}
-
-
-
-
-
-cCriticalSection::~cCriticalSection()
-{
- #ifdef _WIN32
- DeleteCriticalSection(&m_CriticalSection);
- #else
- if (pthread_mutex_destroy(&m_CriticalSection) != 0)
- {
- LOGWARNING("Could not destroy Critical Section!");
- }
- pthread_mutexattr_destroy(&m_Attributes);
- #endif
+ m_IsLocked = 0;
}
+#endif // _DEBUG
@@ -51,15 +21,11 @@ cCriticalSection::~cCriticalSection()
void cCriticalSection::Lock()
{
- #ifdef _WIN32
- EnterCriticalSection(&m_CriticalSection);
- #else
- pthread_mutex_lock(&m_CriticalSection);
- #endif
+ m_Mutex.lock();
#ifdef _DEBUG
m_IsLocked += 1;
- m_OwningThreadID = cIsThread::GetCurrentID();
+ m_OwningThreadID = std::this_thread::get_id();
#endif // _DEBUG
}
@@ -74,11 +40,7 @@ void cCriticalSection::Unlock()
m_IsLocked -= 1;
#endif // _DEBUG
- #ifdef _WIN32
- LeaveCriticalSection(&m_CriticalSection);
- #else
- pthread_mutex_unlock(&m_CriticalSection);
- #endif
+ m_Mutex.unlock();
}
@@ -97,7 +59,7 @@ bool cCriticalSection::IsLocked(void)
bool cCriticalSection::IsLockedByCurrentThread(void)
{
- return ((m_IsLocked > 0) && (m_OwningThreadID == cIsThread::GetCurrentID()));
+ return ((m_IsLocked > 0) && (m_OwningThreadID == std::this_thread::get_id()));
}
#endif // _DEBUG
diff --git a/src/OSSupport/CriticalSection.h b/src/OSSupport/CriticalSection.h
index c3c6e57f0..17fcdfc12 100644
--- a/src/OSSupport/CriticalSection.h
+++ b/src/OSSupport/CriticalSection.h
@@ -1,5 +1,7 @@
#pragma once
+#include <mutex>
+#include <thread>
@@ -8,8 +10,6 @@
class cCriticalSection
{
public:
- cCriticalSection(void);
- ~cCriticalSection();
void Lock(void);
void Unlock(void);
@@ -17,6 +17,7 @@ public:
// IsLocked/IsLockedByCurrentThread are only used in ASSERT statements, but because of the changes with ASSERT they must always be defined
// The fake versions (in Release) will not effect the program in any way
#ifdef _DEBUG
+ cCriticalSection(void);
bool IsLocked(void);
bool IsLockedByCurrentThread(void);
#else
@@ -27,15 +28,10 @@ public:
private:
#ifdef _DEBUG
int m_IsLocked; // Number of times this CS is locked
- unsigned long m_OwningThreadID;
+ std::thread::id m_OwningThreadID;
#endif // _DEBUG
- #ifdef _WIN32
- CRITICAL_SECTION m_CriticalSection;
- #else // _WIN32
- pthread_mutex_t m_CriticalSection;
- pthread_mutexattr_t m_Attributes;
- #endif // else _WIN32
+ std::recursive_mutex m_Mutex;
} ALIGN_8;
diff --git a/src/OSSupport/Event.cpp b/src/OSSupport/Event.cpp
index 87bc110ce..760e536a1 100644
--- a/src/OSSupport/Event.cpp
+++ b/src/OSSupport/Event.cpp
@@ -12,137 +12,59 @@
-cEvent::cEvent(void)
+cEvent::cEvent(void) :
+ m_ShouldWait(true)
{
-#ifdef _WIN32
- m_Event = CreateEvent(nullptr, FALSE, FALSE, nullptr);
- if (m_Event == nullptr)
- {
- LOGERROR("cEvent: cannot create event, GLE = %u. Aborting server.", (unsigned)GetLastError());
- abort();
- }
-#else // *nix
- m_bIsNamed = false;
- m_Event = new sem_t;
- if (sem_init(m_Event, 0, 0))
- {
- // This path is used by MacOS, because it doesn't support unnamed semaphores.
- delete m_Event;
- m_bIsNamed = true;
-
- AString EventName;
- Printf(EventName, "cEvent%p", this);
- m_Event = sem_open(EventName.c_str(), O_CREAT, 777, 0);
- if (m_Event == SEM_FAILED)
- {
- AString error = GetOSErrorString(errno);
- LOGERROR("cEvent: Cannot create event, err = %s. Aborting server.", error.c_str());
- abort();
- }
- // Unlink the semaphore immediately - it will continue to function but will not pollute the namespace
- // We don't store the name, so can't call this in the destructor
- if (sem_unlink(EventName.c_str()) != 0)
- {
- AString error = GetOSErrorString(errno);
- LOGWARN("ERROR: Could not unlink cEvent. (%s)", error.c_str());
- }
- }
-#endif // *nix
}
-cEvent::~cEvent()
+void cEvent::Wait(void)
{
-#ifdef _WIN32
- CloseHandle(m_Event);
-#else
- if (m_bIsNamed)
- {
- if (sem_close(m_Event) != 0)
- {
- AString error = GetOSErrorString(errno);
- LOGERROR("ERROR: Could not close cEvent. (%s)", error.c_str());
- }
- }
- else
+ std::unique_lock<std::mutex> Lock(m_Mutex);
+ while (m_ShouldWait)
{
- sem_destroy(m_Event);
- delete m_Event;
- m_Event = nullptr;
+ m_CondVar.wait(Lock);
}
-#endif
+ m_ShouldWait = true;
}
-void cEvent::Wait(void)
+bool cEvent::Wait(unsigned a_TimeoutMSec)
{
- #ifdef _WIN32
- DWORD res = WaitForSingleObject(m_Event, INFINITE);
- if (res != WAIT_OBJECT_0)
- {
- LOGWARN("cEvent: waiting for the event failed: %u, GLE = %u. Continuing, but server may be unstable.", (unsigned)res, (unsigned)GetLastError());
- }
- #else
- int res = sem_wait(m_Event);
- if (res != 0)
- {
- AString error = GetOSErrorString(errno);
- LOGWARN("cEvent: waiting for the event failed: %i, err = %s. Continuing, but server may be unstable.", res, error.c_str());
- }
- #endif
-}
-
-
-
-
-
-bool cEvent::Wait(int a_TimeoutMSec)
-{
- #ifdef _WIN32
- DWORD res = WaitForSingleObject(m_Event, (DWORD)a_TimeoutMSec);
- switch (res)
+ auto dst = std::chrono::system_clock::now() + std::chrono::milliseconds(a_TimeoutMSec);
+ std::unique_lock<std::mutex> Lock(m_Mutex); // We assume that this lock is acquired without much delay - we are the only user of the mutex
+ while (m_ShouldWait && (std::chrono::system_clock::now() <= dst))
+ {
+ switch (m_CondVar.wait_until(Lock, dst))
{
- case WAIT_OBJECT_0: return true; // Regular event signalled
- case WAIT_TIMEOUT: return false; // Regular event timeout
- default:
+ case std::cv_status::no_timeout:
{
- LOGWARN("cEvent: waiting for the event failed: %u, GLE = %u. Continuing, but server may be unstable.", (unsigned)res, (unsigned)GetLastError());
- return false;
+ // The wait was successful, check for spurious wakeup:
+ if (!m_ShouldWait)
+ {
+ m_ShouldWait = true;
+ return true;
+ }
+ // This was a spurious wakeup, wait again:
+ continue;
}
- }
- #else
- // Get the current time:
- timespec timeout;
- if (clock_gettime(CLOCK_REALTIME, &timeout) == -1)
- {
- LOGWARN("cEvent: Getting current time failed: %i, err = %s. Continuing, but the server may be unstable.", errno, GetOSErrorString(errno).c_str());
- return false;
- }
-
- // Add the specified timeout:
- timeout.tv_sec += a_TimeoutMSec / 1000;
- timeout.tv_nsec += (a_TimeoutMSec % 1000) * 1000000; // 1 msec = 1000000 usec
-
- // Wait with timeout:
- int res = sem_timedwait(m_Event, &timeout);
- switch (res)
- {
- case 0: return true; // Regular event signalled
- case ETIMEDOUT: return false; // Regular even timeout
- default:
+
+ case std::cv_status::timeout:
{
- AString error = GetOSErrorString(errno);
- LOGWARN("cEvent: waiting for the event failed: %i, err = %s. Continuing, but server may be unstable.", res, error.c_str());
+ // The wait timed out, return failure:
return false;
}
- }
- #endif
+ } // switch (wait_until())
+ } // while (m_ShouldWait && not timeout)
+
+ // The wait timed out in the while condition:
+ return false;
}
@@ -151,19 +73,11 @@ bool cEvent::Wait(int a_TimeoutMSec)
void cEvent::Set(void)
{
- #ifdef _WIN32
- if (!SetEvent(m_Event))
- {
- LOGWARN("cEvent: Could not set cEvent: GLE = %u", (unsigned)GetLastError());
- }
- #else
- int res = sem_post(m_Event);
- if (res != 0)
- {
- AString error = GetOSErrorString(errno);
- LOGWARN("cEvent: Could not set cEvent: %i, err = %s", res, error.c_str());
- }
- #endif
+ {
+ std::unique_lock<std::mutex> Lock(m_Mutex);
+ m_ShouldWait = false;
+ }
+ m_CondVar.notify_one();
}
diff --git a/src/OSSupport/Event.h b/src/OSSupport/Event.h
index e2fa65a05..572388a3f 100644
--- a/src/OSSupport/Event.h
+++ b/src/OSSupport/Event.h
@@ -1,16 +1,17 @@
// Event.h
-// Interfaces to the cEvent object representing an OS-specific synchronization primitive that can be waited-for
-// Implemented as an Event on Win and as a 1-semaphore on *nix
+// Interfaces to the cEvent object representing a synchronization primitive that can be waited-for
+// Implemented using C++11 condition variable and mutex
#pragma once
-#ifndef CEVENT_H_INCLUDED
-#define CEVENT_H_INCLUDED
+
+#include <mutex>
+#include <condition_variable>
@@ -20,31 +21,31 @@ class cEvent
{
public:
cEvent(void);
- ~cEvent();
+ /** Waits until the event has been set.
+ If the event has been set before it has been waited for, Wait() returns immediately. */
void Wait(void);
+
+ /** Sets the event - releases one thread that has been waiting in Wait().
+ If there was no thread waiting, the next call to Wait() will not block. */
void Set (void);
/** Waits for the event until either it is signalled, or the (relative) timeout is passed.
Returns true if the event was signalled, false if the timeout was hit or there was an error. */
- bool Wait(int a_TimeoutMSec);
+ bool Wait(unsigned a_TimeoutMSec);
private:
- #ifdef _WIN32
- HANDLE m_Event;
- #else
- sem_t * m_Event;
- bool m_bIsNamed;
- #endif
-} ;
-
-
-
+ /** Used for checking for spurious wakeups. */
+ bool m_ShouldWait;
+ /** Mutex protecting m_ShouldWait from multithreaded access. */
+ std::mutex m_Mutex;
+ /** The condition variable used as the Event. */
+ std::condition_variable m_CondVar;
+} ;
-#endif // CEVENT_H_INCLUDED
diff --git a/src/OSSupport/IsThread.cpp b/src/OSSupport/IsThread.cpp
index 1a436623a..94bed1f56 100644
--- a/src/OSSupport/IsThread.cpp
+++ b/src/OSSupport/IsThread.cpp
@@ -5,49 +5,40 @@
// This class will eventually suupersede the old cThread class
#include "Globals.h"
-
#include "IsThread.h"
-// When in MSVC, the debugger provides "thread naming" by catching special exceptions. Interface here:
#if defined(_MSC_VER) && defined(_DEBUG)
-//
-// Usage: SetThreadName (-1, "MainThread");
-//
-
-// Code adapted from MSDN: http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
-
-const DWORD MS_VC_EXCEPTION = 0x406D1388;
-
-#pragma pack(push, 8)
-typedef struct tagTHREADNAME_INFO
-{
- DWORD dwType; // Must be 0x1000.
- LPCSTR szName; // Pointer to name (in user addr space).
- DWORD dwThreadID; // Thread ID (-1 = caller thread).
- DWORD dwFlags; // Reserved for future use, must be zero.
-} THREADNAME_INFO;
-#pragma pack(pop)
-
-static void SetThreadName(DWORD dwThreadID, const char * threadName)
-{
- THREADNAME_INFO info;
- info.dwType = 0x1000;
- info.szName = threadName;
- info.dwThreadID = dwThreadID;
- info.dwFlags = 0;
+ // Code adapted from MSDN: http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
- __try
- {
- RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR *)&info);
- }
- __except (EXCEPTION_EXECUTE_HANDLER)
+ const DWORD MS_VC_EXCEPTION = 0x406D1388;
+ #pragma pack(push, 8)
+ struct THREADNAME_INFO
+ {
+ DWORD dwType; // Must be 0x1000.
+ LPCSTR szName; // Pointer to name (in user addr space).
+ DWORD dwThreadID; // Thread ID (-1 = caller thread).
+ DWORD dwFlags; // Reserved for future use, must be zero.
+ };
+ #pragma pack(pop)
+
+ /** Sets the name of a thread with the specified ID
+ (When in MSVC, the debugger provides "thread naming" by catching special exceptions)
+ */
+ static void SetThreadName(std::thread * a_Thread, const char * a_ThreadName)
{
+ THREADNAME_INFO info { 0x1000, a_ThreadName, GetThreadId(a_Thread->native_handle()), 0 };
+ __try
+ {
+ RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR *)&info);
+ }
+ __except (EXCEPTION_EXECUTE_HANDLER)
+ {
+ }
}
-}
#endif // _MSC_VER && _DEBUG
@@ -57,13 +48,9 @@ static void SetThreadName(DWORD dwThreadID, const char * threadName)
////////////////////////////////////////////////////////////////////////////////
// cIsThread:
-cIsThread::cIsThread(const AString & iThreadName) :
+cIsThread::cIsThread(const AString & a_ThreadName) :
m_ShouldTerminate(false),
- m_ThreadName(iThreadName),
- #ifdef _WIN32
- m_ThreadID(0),
- #endif
- m_Handle(NULL_HANDLE)
+ m_ThreadName(a_ThreadName)
{
}
@@ -83,35 +70,24 @@ cIsThread::~cIsThread()
bool cIsThread::Start(void)
{
- ASSERT(m_Handle == NULL_HANDLE); // Has already started one thread?
- #ifdef _WIN32
- // Create the thread suspended, so that the mHandle variable is valid in the thread procedure
- m_ThreadID = 0;
- m_Handle = CreateThread(NULL, 0, thrExecute, this, CREATE_SUSPENDED, &m_ThreadID);
- if (m_Handle == NULL)
- {
- LOGERROR("ERROR: Could not create thread \"%s\", GLE = %u!", m_ThreadName.c_str(), (unsigned)GetLastError());
- return false;
- }
- ResumeThread(m_Handle);
-
- #if defined(_DEBUG) && defined(_MSC_VER)
- // Thread naming is available only in MSVC
- if (!m_ThreadName.empty())
- {
- SetThreadName(m_ThreadID, m_ThreadName.c_str());
- }
- #endif // _DEBUG and _MSC_VER
-
- #else // _WIN32
- if (pthread_create(&m_Handle, NULL, thrExecute, this))
+ try
+ {
+ m_Thread = std::thread(&cIsThread::Execute, this);
+
+ #if defined (_MSC_VER) && defined(_DEBUG)
+ if (!m_ThreadName.empty())
{
- LOGERROR("ERROR: Could not create thread \"%s\", !", m_ThreadName.c_str());
- return false;
+ SetThreadName(&m_Thread, m_ThreadName.c_str());
}
- #endif // else _WIN32
+ #endif
- return true;
+ return true;
+ }
+ catch (std::system_error & a_Exception)
+ {
+ LOGERROR("cIsThread::Start error %i: could not construct thread %s; %s", a_Exception.code().value(), m_ThreadName.c_str(), a_Exception.code().message().c_str());
+ return false;
+ }
}
@@ -120,10 +96,12 @@ bool cIsThread::Start(void)
void cIsThread::Stop(void)
{
- if (m_Handle == NULL_HANDLE)
+ if (!m_Thread.joinable())
{
+ // The thread hasn't been started or has already been joined
return;
}
+
m_ShouldTerminate = true;
Wait();
}
@@ -134,59 +112,23 @@ void cIsThread::Stop(void)
bool cIsThread::Wait(void)
{
- if (m_Handle == NULL_HANDLE)
+ LOGD("Waiting for thread %s to finish", m_ThreadName.c_str());
+ if (m_Thread.joinable())
{
- return true;
+ try
+ {
+ m_Thread.join();
+ return true;
+ }
+ catch (std::system_error & a_Exception)
+ {
+ LOGERROR("cIsThread::Wait error %i: could not join thread %s; %s", a_Exception.code().value(), m_ThreadName.c_str(), a_Exception.code().message().c_str());
+ return false;
+ }
}
-
- #ifdef LOGD // ProtoProxy doesn't have LOGD
- LOGD("Waiting for thread %s to finish", m_ThreadName.c_str());
- #endif // LOGD
-
- #ifdef _WIN32
- int res = WaitForSingleObject(m_Handle, INFINITE);
- m_Handle = NULL;
-
- #ifdef LOGD // ProtoProxy doesn't have LOGD
- LOGD("Thread %s finished", m_ThreadName.c_str());
- #endif // LOGD
-
- return (res == WAIT_OBJECT_0);
- #else // _WIN32
- int res = pthread_join(m_Handle, NULL);
- m_Handle = NULL_HANDLE;
-
- #ifdef LOGD // ProtoProxy doesn't have LOGD
- LOGD("Thread %s finished", m_ThreadName.c_str());
- #endif // LOGD
-
- return (res == 0);
- #endif // else _WIN32
-}
-
-
-
-
-unsigned long cIsThread::GetCurrentID(void)
-{
- #ifdef _WIN32
- return (unsigned long) GetCurrentThreadId();
- #else
- return (unsigned long) pthread_self();
- #endif
-}
-
-
-
-
-bool cIsThread::IsCurrentThread(void) const
-{
- #ifdef _WIN32
- return (GetCurrentThreadId() == m_ThreadID);
- #else
- return (m_Handle == pthread_self());
- #endif
+ LOGD("Thread %s finished", m_ThreadName.c_str());
+ return true;
}
diff --git a/src/OSSupport/IsThread.h b/src/OSSupport/IsThread.h
index 5c8d28d2d..131c6950e 100644
--- a/src/OSSupport/IsThread.h
+++ b/src/OSSupport/IsThread.h
@@ -16,8 +16,7 @@ In the descending class' constructor call the Start() method to start the thread
#pragma once
-#ifndef CISTHREAD_H_INCLUDED
-#define CISTHREAD_H_INCLUDED
+#include <thread>
@@ -33,7 +32,7 @@ protected:
volatile bool m_ShouldTerminate;
public:
- cIsThread(const AString & iThreadName);
+ cIsThread(const AString & a_ThreadName);
virtual ~cIsThread();
/// Starts the thread; returns without waiting for the actual start
@@ -45,56 +44,14 @@ public:
/// Waits for the thread to finish. Doesn't signalize the ShouldTerminate flag
bool Wait(void);
- /// Returns the OS-dependent thread ID for the caller's thread
- static unsigned long GetCurrentID(void);
-
/** Returns true if the thread calling this function is the thread contained within this object. */
- bool IsCurrentThread(void) const;
+ bool IsCurrentThread(void) const { return std::this_thread::get_id() == m_Thread.get_id(); }
protected:
AString m_ThreadName;
-
- // Value used for "no handle":
- #ifdef _WIN32
- #define NULL_HANDLE NULL
- #else
- #define NULL_HANDLE 0
- #endif
-
- #ifdef _WIN32
-
- DWORD m_ThreadID;
- HANDLE m_Handle;
-
- static DWORD __stdcall thrExecute(LPVOID a_Param)
- {
- // Create a window so that the thread can be identified by 3rd party tools:
- HWND IdentificationWnd = CreateWindowA("STATIC", ((cIsThread *)a_Param)->m_ThreadName.c_str(), 0, 0, 0, 0, WS_OVERLAPPED, NULL, NULL, NULL, NULL);
-
- // Run the thread:
- ((cIsThread *)a_Param)->Execute();
-
- // Destroy the identification window:
- DestroyWindow(IdentificationWnd);
-
- return 0;
- }
-
- #else // _WIN32
-
- pthread_t m_Handle;
-
- static void * thrExecute(void * a_Param)
- {
- (static_cast<cIsThread *>(a_Param))->Execute();
- return NULL;
- }
-
- #endif // else _WIN32
+ std::thread m_Thread;
} ;
-
-#endif // CISTHREAD_H_INCLUDED
diff --git a/src/OSSupport/Queue.h b/src/OSSupport/Queue.h
index 8d096fe29..82f221453 100644
--- a/src/OSSupport/Queue.h
+++ b/src/OSSupport/Queue.h
@@ -163,6 +163,29 @@ public:
return false;
}
+
+ /** Removes all items for which the predicate returns true. */
+ template <class Predicate>
+ void RemoveIf(Predicate a_Predicate)
+ {
+ cCSLock Lock(m_CS);
+ for (auto itr = m_Contents.begin(); itr != m_Contents.end();)
+ {
+ if (a_Predicate(*itr))
+ {
+ auto itr2 = itr;
+ ++itr2;
+ m_Contents.erase(itr);
+ m_evtRemoved.Set();
+ itr = itr2;
+ }
+ else
+ {
+ ++itr;
+ }
+ } // for itr - m_Contents[]
+ }
+
private:
/// The contents of the queue
QueueType m_Contents;
diff --git a/src/OSSupport/Sleep.cpp b/src/OSSupport/Sleep.cpp
deleted file mode 100644
index 297d668d7..000000000
--- a/src/OSSupport/Sleep.cpp
+++ /dev/null
@@ -1,19 +0,0 @@
-
-#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
-
-#ifndef _WIN32
- #include <unistd.h>
-#endif
-
-
-
-
-
-void cSleep::MilliSleep( unsigned int a_MilliSeconds)
-{
-#ifdef _WIN32
- Sleep(a_MilliSeconds); // Don't tick too much
-#else
- usleep(a_MilliSeconds*1000);
-#endif
-}
diff --git a/src/OSSupport/Sleep.h b/src/OSSupport/Sleep.h
deleted file mode 100644
index 57d29682c..000000000
--- a/src/OSSupport/Sleep.h
+++ /dev/null
@@ -1,7 +0,0 @@
-#pragma once
-
-class cSleep
-{
-public:
- static void MilliSleep( unsigned int a_MilliSeconds);
-};
diff --git a/src/OSSupport/Socket.h b/src/OSSupport/Socket.h
index e4ec895cb..9ec8c1111 100644
--- a/src/OSSupport/Socket.h
+++ b/src/OSSupport/Socket.h
@@ -74,7 +74,7 @@ public:
inline static bool IsSocketError(int a_ReturnedValue)
{
#ifdef _WIN32
- return (a_ReturnedValue == SOCKET_ERROR || a_ReturnedValue == 0);
+ return ((a_ReturnedValue == SOCKET_ERROR) || (a_ReturnedValue == 0));
#else
return (a_ReturnedValue <= 0);
#endif
diff --git a/src/OSSupport/SocketThreads.cpp b/src/OSSupport/SocketThreads.cpp
index 7a3ef4274..153d6ed1d 100644
--- a/src/OSSupport/SocketThreads.cpp
+++ b/src/OSSupport/SocketThreads.cpp
@@ -86,7 +86,8 @@ void cSocketThreads::RemoveClient(const cCallback * a_Client)
}
} // for itr - m_Threads[]
- ASSERT(!"Removing an unknown client");
+ // This client wasn't found.
+ // It's not an error, because it may have been removed by a different thread in the meantime.
}
@@ -491,10 +492,17 @@ void cSocketThreads::cSocketThread::ReadFromSockets(fd_set * a_Read)
{
case sSlot::ssNormal:
{
- // Notify the callback that the remote has closed the socket; keep the slot
- m_Slots[i].m_Client->SocketClosed();
+ // Close the socket on our side:
m_Slots[i].m_State = sSlot::ssRemoteClosed;
m_Slots[i].m_Socket.CloseSocket();
+
+ // Notify the callback that the remote has closed the socket, *after* removing the socket:
+ cCallback * client = m_Slots[i].m_Client;
+ m_Slots[i] = m_Slots[--m_NumSlots];
+ if (client != nullptr)
+ {
+ client->SocketClosed();
+ }
break;
}
case sSlot::ssWritingRestOut:
diff --git a/src/OSSupport/StackTrace.cpp b/src/OSSupport/StackTrace.cpp
new file mode 100644
index 000000000..a56568457
--- /dev/null
+++ b/src/OSSupport/StackTrace.cpp
@@ -0,0 +1,44 @@
+
+// StackTrace.cpp
+
+// Implements the functions to print current stack traces
+
+#include "Globals.h"
+#include "StackTrace.h"
+#ifdef _WIN32
+ #include "../StackWalker.h"
+#else
+ #include <execinfo.h>
+ #include <unistd.h>
+#endif
+
+
+
+
+
+void PrintStackTrace(void)
+{
+ #ifdef _WIN32
+ // Reuse the StackWalker from the LeakFinder project already bound to MCS
+ // Define a subclass of the StackWalker that outputs everything to stdout
+ class PrintingStackWalker :
+ public StackWalker
+ {
+ virtual void OnOutput(LPCSTR szText) override
+ {
+ puts(szText);
+ }
+ } sw;
+ sw.ShowCallstack();
+ #else
+ // Use the backtrace() function to get and output the stackTrace:
+ // Code adapted from http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes
+ void * stackTrace[30];
+ size_t numItems = backtrace(stackTrace, ARRAYCOUNT(stackTrace));
+ backtrace_symbols_fd(stackTrace, numItems, STDERR_FILENO);
+ #endif
+}
+
+
+
+
diff --git a/src/OSSupport/StackTrace.h b/src/OSSupport/StackTrace.h
new file mode 100644
index 000000000..228a00077
--- /dev/null
+++ b/src/OSSupport/StackTrace.h
@@ -0,0 +1,15 @@
+
+// StackTrace.h
+
+// Declares the functions to print current stack trace
+
+
+
+
+
+/** Prints the stacktrace for the current thread. */
+extern void PrintStackTrace(void);
+
+
+
+
diff --git a/src/OSSupport/Thread.cpp b/src/OSSupport/Thread.cpp
deleted file mode 100644
index faaccce96..000000000
--- a/src/OSSupport/Thread.cpp
+++ /dev/null
@@ -1,137 +0,0 @@
-
-#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
-
-
-
-
-
-// When in MSVC, the debugger provides "thread naming" by catching special exceptions. Interface here:
-#ifdef _MSC_VER
-//
-// Usage: SetThreadName (-1, "MainThread");
-//
-
-// Code adapted from MSDN: http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
-
-const DWORD MS_VC_EXCEPTION = 0x406D1388;
-
-#pragma pack(push, 8)
-typedef struct tagTHREADNAME_INFO
-{
- DWORD dwType; // Must be 0x1000.
- LPCSTR szName; // Pointer to name (in user addr space).
- DWORD dwThreadID; // Thread ID (-1 = caller thread).
- DWORD dwFlags; // Reserved for future use, must be zero.
-} THREADNAME_INFO;
-#pragma pack(pop)
-
-static void SetThreadName(DWORD dwThreadID, const char * threadName)
-{
- THREADNAME_INFO info;
- info.dwType = 0x1000;
- info.szName = threadName;
- info.dwThreadID = dwThreadID;
- info.dwFlags = 0;
-
- __try
- {
- RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR *)&info);
- }
- __except (EXCEPTION_EXECUTE_HANDLER)
- {
- }
-}
-#endif // _MSC_VER
-
-
-
-
-
-cThread::cThread( ThreadFunc a_ThreadFunction, void* a_Param, const char* a_ThreadName /* = 0 */)
- : m_ThreadFunction( a_ThreadFunction)
- , m_Param( a_Param)
- , m_Event( new cEvent())
- , m_StopEvent( 0)
-{
- if (a_ThreadName)
- {
- m_ThreadName.assign(a_ThreadName);
- }
-}
-
-
-
-
-
-cThread::~cThread()
-{
- delete m_Event;
- m_Event = NULL;
-
- if (m_StopEvent)
- {
- m_StopEvent->Wait();
- delete m_StopEvent;
- m_StopEvent = NULL;
- }
-}
-
-
-
-
-
-void cThread::Start( bool a_bWaitOnDelete /* = true */)
-{
- if (a_bWaitOnDelete)
- m_StopEvent = new cEvent();
-
-#ifndef _WIN32
- pthread_t SndThread;
- if (pthread_create( &SndThread, NULL, MyThread, this))
- LOGERROR("ERROR: Could not create thread!");
-#else
- DWORD ThreadID = 0;
- HANDLE hThread = CreateThread(NULL // security
- , 0 // stack size
- , (LPTHREAD_START_ROUTINE) MyThread // function name
- , this // parameters
- , 0 // flags
- , &ThreadID); // thread id
- CloseHandle( hThread);
-
- #ifdef _MSC_VER
- if (!m_ThreadName.empty())
- {
- SetThreadName(ThreadID, m_ThreadName.c_str());
- }
- #endif // _MSC_VER
-#endif
-
- // Wait until thread has actually been created
- m_Event->Wait();
-}
-
-
-
-
-
-#ifdef _WIN32
-unsigned long cThread::MyThread(void* a_Param)
-#else
-void *cThread::MyThread( void *a_Param)
-#endif
-{
- cThread* self = (cThread*)a_Param;
- cEvent* StopEvent = self->m_StopEvent;
-
- ThreadFunc* ThreadFunction = self->m_ThreadFunction;
- void* ThreadParam = self->m_Param;
-
- // Set event to let other thread know this thread has been created and it's safe to delete the cThread object
- self->m_Event->Set();
-
- ThreadFunction( ThreadParam);
-
- if (StopEvent) StopEvent->Set();
- return 0;
-}
diff --git a/src/OSSupport/Thread.h b/src/OSSupport/Thread.h
deleted file mode 100644
index 7ee352c82..000000000
--- a/src/OSSupport/Thread.h
+++ /dev/null
@@ -1,26 +0,0 @@
-#pragma once
-
-class cThread
-{
-public:
- typedef void (ThreadFunc)(void*);
- cThread( ThreadFunc a_ThreadFunction, void* a_Param, const char* a_ThreadName = 0);
- ~cThread();
-
- void Start( bool a_bWaitOnDelete = true);
- void WaitForThread();
-private:
- ThreadFunc* m_ThreadFunction;
-
-#ifdef _WIN32
- static unsigned long MyThread(void* a_Param);
-#else
- static void *MyThread( void *lpParam);
-#endif
-
- void* m_Param;
- cEvent* m_Event;
- cEvent* m_StopEvent;
-
- AString m_ThreadName;
-};
diff --git a/src/OSSupport/Timer.cpp b/src/OSSupport/Timer.cpp
deleted file mode 100644
index fd838dd0d..000000000
--- a/src/OSSupport/Timer.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-
-#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
-
-#include "Timer.h"
-
-
-
-
-
-
-cTimer::cTimer(void)
-{
- #ifdef _WIN32
- QueryPerformanceFrequency(&m_TicksPerSecond);
- #endif
-}
-
-
-
-
-
-long long cTimer::GetNowTime(void)
-{
- #ifdef _WIN32
- LARGE_INTEGER now;
- QueryPerformanceCounter(&now);
- return ((now.QuadPart * 1000) / m_TicksPerSecond.QuadPart);
- #else
- struct timeval now;
- gettimeofday(&now, NULL);
- return (long long)now.tv_sec * 1000 + (long long)now.tv_usec / 1000;
- #endif
-}
-
-
-
-
diff --git a/src/OSSupport/Timer.h b/src/OSSupport/Timer.h
deleted file mode 100644
index a059daa41..000000000
--- a/src/OSSupport/Timer.h
+++ /dev/null
@@ -1,32 +0,0 @@
-
-// Timer.h
-
-// Declares the cTimer class representing an OS-independent of retrieving current time with msec accuracy
-
-
-
-
-
-#pragma once
-
-
-
-
-
-class cTimer
-{
-public:
- cTimer(void);
-
- // Returns the current time expressed in milliseconds
- long long GetNowTime(void);
-private:
-
- #ifdef _WIN32
- LARGE_INTEGER m_TicksPerSecond;
- #endif
-} ;
-
-
-
-