Remove tinythread from PluginManager

Remove useless tinythread import in PlugLoad-windows.cpp

Remove seemingly useless tinythread import in LuaTools.cpp

Factor out tinythread in LuaApi.cpp

Removed unused tinythread in LuaWrapper.cpp

Removed unused tinythread include in LuaTypes.cpp

Removed unused tinythread include in ColorText.cpp

Factor out tinythread in Console.h

Factor out tinythread in Console-posix.cpp

Factor out tinythread in Console-windows.cpp

Factor out tinythread in renderer_light

Factor out tinythread in DataDefs.cpp

Remove unused tinythread include in RemoteClient.cpp

Add includes for new mutex and conditional_variable usages in PluginManager

Factor out tinythread from devel/memview, renderermax/renderer_light, and rendermax/renderer_opengl plugins

Remove usages of tinythread in various CMakeLists.txt files, in .ycm_extra_conf.py, and delete tinythread itself

Delete tinythread from LISCENSE.rst

excise tinythread: fix deadlock in pluginmanager

excise tinythread: remove improper header

excise tinythread: fix double unlock. fix plugin typo
develop
Paxton Schweigert 2022-12-20 17:56:58 -08:00 committed by dhthwy
parent d24f1a1b2c
commit 54769ebdbf
27 changed files with 82 additions and 1160 deletions

@ -19,7 +19,6 @@ default_flags = [
'-I','depends/md5', '-I','depends/md5',
'-I','depends/jsoncpp/include', '-I','depends/jsoncpp/include',
'-I','depends/tinyxml', '-I','depends/tinyxml',
'-I','depends/tthread',
'-I','depends/clsocket/src', '-I','depends/clsocket/src',
'-x','c++', '-x','c++',
'-D','PROTOBUF_USE_DLLS', '-D','PROTOBUF_USE_DLLS',

@ -384,7 +384,6 @@ else()
endif() endif()
include_directories(depends/lodepng) include_directories(depends/lodepng)
include_directories(depends/tthread)
include_directories(depends/clsocket/src) include_directories(depends/clsocket/src)
include_directories(depends/xlsxio/include) include_directories(depends/xlsxio/include)

@ -31,7 +31,6 @@ luacov_ MIT \(c\) 2007 - 2018 Hisham Muhammad
luafilesystem_ MIT \(c\) 2003-2014, Kepler Project luafilesystem_ MIT \(c\) 2003-2014, Kepler Project
lua-profiler_ MIT \(c\) 2002,2003,2004 Pepperfish lua-profiler_ MIT \(c\) 2002,2003,2004 Pepperfish
protobuf_ BSD 3-clause \(c\) 2008, Google Inc. protobuf_ BSD 3-clause \(c\) 2008, Google Inc.
tinythread_ Zlib \(c\) 2010, Marcus Geelnard
tinyxml_ Zlib \(c\) 2000-2006, Lee Thomason tinyxml_ Zlib \(c\) 2000-2006, Lee Thomason
UTF-8-decoder_ MIT \(c\) 2008-2010, Bjoern Hoehrmann UTF-8-decoder_ MIT \(c\) 2008-2010, Bjoern Hoehrmann
xlsxio_ MIT \(c\) 2016-2020, Brecht Sanders xlsxio_ MIT \(c\) 2016-2020, Brecht Sanders
@ -52,7 +51,6 @@ googletest_ BSD 3-Clause \(c\) 2008, Google Inc.
.. _luafilesystem: https://github.com/keplerproject/luafilesystem .. _luafilesystem: https://github.com/keplerproject/luafilesystem
.. _lua-profiler: http://lua-users.org/wiki/PepperfishProfiler .. _lua-profiler: http://lua-users.org/wiki/PepperfishProfiler
.. _protobuf: https://github.com/google/protobuf .. _protobuf: https://github.com/google/protobuf
.. _tinythread: http://tinythreadpp.bitsnbites.eu/
.. _tinyxml: http://www.sourceforge.net/projects/tinyxml .. _tinyxml: http://www.sourceforge.net/projects/tinyxml
.. _UTF-8-decoder: http://bjoern.hoehrmann.de/utf-8/decoder/dfa .. _UTF-8-decoder: http://bjoern.hoehrmann.de/utf-8/decoder/dfa
.. _xlsxio: https://github.com/brechtsanders/xlsxio .. _xlsxio: https://github.com/brechtsanders/xlsxio

@ -25,7 +25,6 @@ if(NOT TinyXML_FOUND)
add_subdirectory(tinyxml) add_subdirectory(tinyxml)
endif() endif()
add_subdirectory(tthread)
option(JSONCPP_WITH_TESTS "Compile and (for jsoncpp_check) run JsonCpp test executables" OFF) option(JSONCPP_WITH_TESTS "Compile and (for jsoncpp_check) run JsonCpp test executables" OFF)
option(JSONCPP_WITH_POST_BUILD_UNITTEST "Automatically run unit-tests as a post build step" OFF) option(JSONCPP_WITH_POST_BUILD_UNITTEST "Automatically run unit-tests as a post build step" OFF)
option(JSONCPP_BUILD_SHARED_LIBS "Build jsoncpp_lib as a shared library." OFF) option(JSONCPP_BUILD_SHARED_LIBS "Build jsoncpp_lib as a shared library." OFF)

@ -1,6 +0,0 @@
project(dfhack-tinythread)
add_library(dfhack-tinythread STATIC EXCLUDE_FROM_ALL tinythread.cpp tinythread.h)
if(UNIX)
target_link_libraries(dfhack-tinythread pthread)
endif()
ide_folder(dfhack-tinythread "Depends")

@ -1,313 +0,0 @@
/* -*- mode: c++; tab-width: 2; indent-tabs-mode: nil; -*-
Copyright (c) 2010-2012 Marcus Geelnard
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include <exception>
#include "tinythread.h"
#if defined(_TTHREAD_POSIX_)
#include <unistd.h>
#include <map>
#elif defined(_TTHREAD_WIN32_)
#include <process.h>
#endif
namespace tthread {
//------------------------------------------------------------------------------
// condition_variable
//------------------------------------------------------------------------------
// NOTE 1: The Win32 implementation of the condition_variable class is based on
// the corresponding implementation in GLFW, which in turn is based on a
// description by Douglas C. Schmidt and Irfan Pyarali:
// http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
//
// NOTE 2: Windows Vista actually has native support for condition variables
// (InitializeConditionVariable, WakeConditionVariable, etc), but we want to
// be portable with pre-Vista Windows versions, so TinyThread++ does not use
// Vista condition variables.
//------------------------------------------------------------------------------
#if defined(_TTHREAD_WIN32_)
#define _CONDITION_EVENT_ONE 0
#define _CONDITION_EVENT_ALL 1
#endif
#if defined(_TTHREAD_WIN32_)
condition_variable::condition_variable() : mWaitersCount(0)
{
mEvents[_CONDITION_EVENT_ONE] = CreateEvent(NULL, FALSE, FALSE, NULL);
mEvents[_CONDITION_EVENT_ALL] = CreateEvent(NULL, TRUE, FALSE, NULL);
InitializeCriticalSection(&mWaitersCountLock);
}
#endif
#if defined(_TTHREAD_WIN32_)
condition_variable::~condition_variable()
{
CloseHandle(mEvents[_CONDITION_EVENT_ONE]);
CloseHandle(mEvents[_CONDITION_EVENT_ALL]);
DeleteCriticalSection(&mWaitersCountLock);
}
#endif
#if defined(_TTHREAD_WIN32_)
void condition_variable::_wait()
{
// Wait for either event to become signaled due to notify_one() or
// notify_all() being called
int result = WaitForMultipleObjects(2, mEvents, FALSE, INFINITE);
// Check if we are the last waiter
EnterCriticalSection(&mWaitersCountLock);
-- mWaitersCount;
bool lastWaiter = (result == (WAIT_OBJECT_0 + _CONDITION_EVENT_ALL)) &&
(mWaitersCount == 0);
LeaveCriticalSection(&mWaitersCountLock);
// If we are the last waiter to be notified to stop waiting, reset the event
if(lastWaiter)
ResetEvent(mEvents[_CONDITION_EVENT_ALL]);
}
#endif
#if defined(_TTHREAD_WIN32_)
void condition_variable::notify_one()
{
// Are there any waiters?
EnterCriticalSection(&mWaitersCountLock);
bool haveWaiters = (mWaitersCount > 0);
LeaveCriticalSection(&mWaitersCountLock);
// If we have any waiting threads, send them a signal
if(haveWaiters)
SetEvent(mEvents[_CONDITION_EVENT_ONE]);
}
#endif
#if defined(_TTHREAD_WIN32_)
void condition_variable::notify_all()
{
// Are there any waiters?
EnterCriticalSection(&mWaitersCountLock);
bool haveWaiters = (mWaitersCount > 0);
LeaveCriticalSection(&mWaitersCountLock);
// If we have any waiting threads, send them a signal
if(haveWaiters)
SetEvent(mEvents[_CONDITION_EVENT_ALL]);
}
#endif
//------------------------------------------------------------------------------
// POSIX pthread_t to unique thread::id mapping logic.
// Note: Here we use a global thread safe std::map to convert instances of
// pthread_t to small thread identifier numbers (unique within one process).
// This method should be portable across different POSIX implementations.
//------------------------------------------------------------------------------
#if defined(_TTHREAD_POSIX_)
static thread::id _pthread_t_to_ID(const pthread_t &aHandle)
{
static mutex idMapLock;
static std::map<pthread_t, unsigned long int> idMap;
static unsigned long int idCount(1);
lock_guard<mutex> guard(idMapLock);
if(idMap.find(aHandle) == idMap.end())
idMap[aHandle] = idCount ++;
return thread::id(idMap[aHandle]);
}
#endif // _TTHREAD_POSIX_
//------------------------------------------------------------------------------
// thread
//------------------------------------------------------------------------------
/// Information to pass to the new thread (what to run).
struct _thread_start_info {
void (*mFunction)(void *); ///< Pointer to the function to be executed.
void * mArg; ///< Function argument for the thread function.
thread * mThread; ///< Pointer to the thread object.
};
// Thread wrapper function.
#if defined(_TTHREAD_WIN32_)
unsigned WINAPI thread::wrapper_function(void * aArg)
#elif defined(_TTHREAD_POSIX_)
void * thread::wrapper_function(void * aArg)
#endif
{
// Get thread startup information
_thread_start_info * ti = (_thread_start_info *) aArg;
try
{
// Call the actual client thread function
ti->mFunction(ti->mArg);
}
catch(...)
{
// Uncaught exceptions will terminate the application (default behavior
// according to C++11)
std::terminate();
}
#if 0
// DFHack fix: this code prevents join from freeing thread resources.
// The thread is no longer executing
lock_guard<mutex> guard(ti->mThread->mDataMutex);
ti->mThread->mNotAThread = true;
#endif
// The thread is responsible for freeing the startup information
delete ti;
return 0;
}
thread::thread(void (*aFunction)(void *), void * aArg)
{
// Serialize access to this thread structure
lock_guard<mutex> guard(mDataMutex);
// Fill out the thread startup information (passed to the thread wrapper,
// which will eventually free it)
_thread_start_info * ti = new _thread_start_info;
ti->mFunction = aFunction;
ti->mArg = aArg;
ti->mThread = this;
// The thread is now alive
mNotAThread = false;
// Create the thread
#if defined(_TTHREAD_WIN32_)
mHandle = (HANDLE) _beginthreadex(0, 0, wrapper_function, (void *) ti, 0, &mWin32ThreadID);
#elif defined(_TTHREAD_POSIX_)
if(pthread_create(&mHandle, NULL, wrapper_function, (void *) ti) != 0)
mHandle = 0;
#endif
// Did we fail to create the thread?
if(!mHandle)
{
mNotAThread = true;
delete ti;
}
}
thread::~thread()
{
if(joinable())
std::terminate();
}
void thread::join()
{
if(joinable())
{
#if defined(_TTHREAD_WIN32_)
WaitForSingleObject(mHandle, INFINITE);
CloseHandle(mHandle);
#elif defined(_TTHREAD_POSIX_)
pthread_join(mHandle, NULL);
#endif
#if 1
// DFHack patch: moved here from the wrapper function
lock_guard<mutex> guard(mDataMutex);
mNotAThread = true;
#endif
}
}
bool thread::joinable() const
{
mDataMutex.lock();
bool result = !mNotAThread;
mDataMutex.unlock();
return result;
}
void thread::detach()
{
mDataMutex.lock();
if(!mNotAThread)
{
#if defined(_TTHREAD_WIN32_)
CloseHandle(mHandle);
#elif defined(_TTHREAD_POSIX_)
pthread_detach(mHandle);
#endif
mNotAThread = true;
}
mDataMutex.unlock();
}
thread::id thread::get_id() const
{
if(!joinable())
return id();
#if defined(_TTHREAD_WIN32_)
return id((unsigned long int) mWin32ThreadID);
#elif defined(_TTHREAD_POSIX_)
return _pthread_t_to_ID(mHandle);
#endif
}
unsigned thread::hardware_concurrency()
{
#if defined(_TTHREAD_WIN32_)
SYSTEM_INFO si;
GetSystemInfo(&si);
return (int) si.dwNumberOfProcessors;
#elif defined(_SC_NPROCESSORS_ONLN)
return (int) sysconf(_SC_NPROCESSORS_ONLN);
#elif defined(_SC_NPROC_ONLN)
return (int) sysconf(_SC_NPROC_ONLN);
#else
// The standard requires this function to return zero if the number of
// hardware cores could not be determined.
return 0;
#endif
}
//------------------------------------------------------------------------------
// this_thread
//------------------------------------------------------------------------------
thread::id this_thread::get_id()
{
#if defined(_TTHREAD_WIN32_)
return thread::id((unsigned long int) GetCurrentThreadId());
#elif defined(_TTHREAD_POSIX_)
return _pthread_t_to_ID(pthread_self());
#endif
}
}

@ -1,714 +0,0 @@
/* -*- mode: c++; tab-width: 2; indent-tabs-mode: nil; -*-
Copyright (c) 2010-2012 Marcus Geelnard
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef _TINYTHREAD_H_
#define _TINYTHREAD_H_
/// @file
/// @mainpage TinyThread++ API Reference
///
/// @section intro_sec Introduction
/// TinyThread++ is a minimal, portable implementation of basic threading
/// classes for C++.
///
/// They closely mimic the functionality and naming of the C++11 standard, and
/// should be easily replaceable with the corresponding std:: variants.
///
/// @section port_sec Portability
/// The Win32 variant uses the native Win32 API for implementing the thread
/// classes, while for other systems, the POSIX threads API (pthread) is used.
///
/// @section class_sec Classes
/// In order to mimic the threading API of the C++11 standard, subsets of
/// several classes are provided. The fundamental classes are:
/// @li tthread::thread
/// @li tthread::mutex
/// @li tthread::recursive_mutex
/// @li tthread::condition_variable
/// @li tthread::lock_guard
///
/// @section misc_sec Miscellaneous
/// The following special keywords are available: #thread_local.
///
/// For more detailed information (including additional classes), browse the
/// different sections of this documentation. A good place to start is:
/// tinythread.h.
// Which platform are we on?
#if !defined(_TTHREAD_PLATFORM_DEFINED_)
#if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__)
#define _TTHREAD_WIN32_
#else
#define _TTHREAD_POSIX_
#endif
#define _TTHREAD_PLATFORM_DEFINED_
#endif
// Platform specific includes
#if defined(_TTHREAD_WIN32_)
#define NOMINMAX
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#define __UNDEF_LEAN_AND_MEAN
#endif
#include <windows.h>
#ifdef __UNDEF_LEAN_AND_MEAN
#undef WIN32_LEAN_AND_MEAN
#undef __UNDEF_LEAN_AND_MEAN
#endif
#else
#include <pthread.h>
#include <signal.h>
#include <sched.h>
#include <unistd.h>
#endif
// Generic includes
#include <ostream>
/// TinyThread++ version (major number).
#define TINYTHREAD_VERSION_MAJOR 1
/// TinyThread++ version (minor number).
#define TINYTHREAD_VERSION_MINOR 1
/// TinyThread++ version (full version).
#define TINYTHREAD_VERSION (TINYTHREAD_VERSION_MAJOR * 100 + TINYTHREAD_VERSION_MINOR)
// Do we have a fully featured C++11 compiler?
#if (__cplusplus > 199711L) || (defined(__STDCXX_VERSION__) && (__STDCXX_VERSION__ >= 201001L))
#define _TTHREAD_CPP11_
#endif
// ...at least partial C++11?
#if defined(_TTHREAD_CPP11_) || defined(__GXX_EXPERIMENTAL_CXX0X__) || defined(__GXX_EXPERIMENTAL_CPP0X__)
#define _TTHREAD_CPP11_PARTIAL_
#endif
// Macro for disabling assignments of objects.
#ifdef _TTHREAD_CPP11_PARTIAL_
#define _TTHREAD_DISABLE_ASSIGNMENT(name) \
name(const name&) = delete; \
name& operator=(const name&) = delete;
#else
#define _TTHREAD_DISABLE_ASSIGNMENT(name) \
name(const name&); \
name& operator=(const name&);
#endif
/// @def thread_local
/// Thread local storage keyword.
/// A variable that is declared with the @c thread_local keyword makes the
/// value of the variable local to each thread (known as thread-local storage,
/// or TLS). Example usage:
/// @code
/// // This variable is local to each thread.
/// thread_local int variable;
/// @endcode
/// @note The @c thread_local keyword is a macro that maps to the corresponding
/// compiler directive (e.g. @c __declspec(thread)). While the C++11 standard
/// allows for non-trivial types (e.g. classes with constructors and
/// destructors) to be declared with the @c thread_local keyword, most pre-C++11
/// compilers only allow for trivial types (e.g. @c int). So, to guarantee
/// portable code, only use trivial types for thread local storage.
/// @note This directive is currently not supported on Mac OS X (it will give
/// a compiler error), since compile-time TLS is not supported in the Mac OS X
/// executable format. Also, some older versions of MinGW (before GCC 4.x) do
/// not support this directive.
/// @hideinitializer
#if !defined(_TTHREAD_CPP11_) && !defined(thread_local)
#if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_CC) || defined(__IBMCPP__)
#define thread_local __thread
#else
#define thread_local __declspec(thread)
#endif
#endif
/// Main name space for TinyThread++.
/// This namespace is more or less equivalent to the @c std namespace for the
/// C++11 thread classes. For instance, the tthread::mutex class corresponds to
/// the std::mutex class.
namespace tthread {
/// Mutex class.
/// This is a mutual exclusion object for synchronizing access to shared
/// memory areas for several threads. The mutex is non-recursive (i.e. a
/// program may deadlock if the thread that owns a mutex object calls lock()
/// on that object).
/// @see recursive_mutex
class mutex {
public:
/// Constructor.
mutex()
#if defined(_TTHREAD_WIN32_)
: mAlreadyLocked(false)
#endif
{
#if defined(_TTHREAD_WIN32_)
InitializeCriticalSection(&mHandle);
#else
pthread_mutex_init(&mHandle, NULL);
#endif
}
/// Destructor.
~mutex()
{
#if defined(_TTHREAD_WIN32_)
DeleteCriticalSection(&mHandle);
#else
pthread_mutex_destroy(&mHandle);
#endif
}
/// Lock the mutex.
/// The method will block the calling thread until a lock on the mutex can
/// be obtained. The mutex remains locked until @c unlock() is called.
/// @see lock_guard
inline void lock()
{
#if defined(_TTHREAD_WIN32_)
EnterCriticalSection(&mHandle);
while(mAlreadyLocked) Sleep(1000); // Simulate deadlock...
mAlreadyLocked = true;
#else
pthread_mutex_lock(&mHandle);
#endif
}
/// Try to lock the mutex.
/// The method will try to lock the mutex. If it fails, the function will
/// return immediately (non-blocking).
/// @return @c true if the lock was acquired, or @c false if the lock could
/// not be acquired.
inline bool try_lock()
{
#if defined(_TTHREAD_WIN32_)
bool ret = (TryEnterCriticalSection(&mHandle) ? true : false);
if(ret && mAlreadyLocked)
{
LeaveCriticalSection(&mHandle);
ret = false;
}
return ret;
#else
return (pthread_mutex_trylock(&mHandle) == 0) ? true : false;
#endif
}
/// Unlock the mutex.
/// If any threads are waiting for the lock on this mutex, one of them will
/// be unblocked.
inline void unlock()
{
#if defined(_TTHREAD_WIN32_)
mAlreadyLocked = false;
LeaveCriticalSection(&mHandle);
#else
pthread_mutex_unlock(&mHandle);
#endif
}
_TTHREAD_DISABLE_ASSIGNMENT(mutex)
private:
#if defined(_TTHREAD_WIN32_)
CRITICAL_SECTION mHandle;
bool mAlreadyLocked;
#else
pthread_mutex_t mHandle;
#endif
friend class condition_variable;
};
/// Recursive mutex class.
/// This is a mutual exclusion object for synchronizing access to shared
/// memory areas for several threads. The mutex is recursive (i.e. a thread
/// may lock the mutex several times, as long as it unlocks the mutex the same
/// number of times).
/// @see mutex
class recursive_mutex {
public:
/// Constructor.
recursive_mutex()
{
#if defined(_TTHREAD_WIN32_)
InitializeCriticalSection(&mHandle);
#else
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mHandle, &attr);
#endif
}
/// Destructor.
~recursive_mutex()
{
#if defined(_TTHREAD_WIN32_)
DeleteCriticalSection(&mHandle);
#else
pthread_mutex_destroy(&mHandle);
#endif
}
/// Lock the mutex.
/// The method will block the calling thread until a lock on the mutex can
/// be obtained. The mutex remains locked until @c unlock() is called.
/// @see lock_guard
inline void lock()
{
#if defined(_TTHREAD_WIN32_)
EnterCriticalSection(&mHandle);
#else
pthread_mutex_lock(&mHandle);
#endif
}
/// Try to lock the mutex.
/// The method will try to lock the mutex. If it fails, the function will
/// return immediately (non-blocking).
/// @return @c true if the lock was acquired, or @c false if the lock could
/// not be acquired.
inline bool try_lock()
{
#if defined(_TTHREAD_WIN32_)
return TryEnterCriticalSection(&mHandle) ? true : false;
#else
return (pthread_mutex_trylock(&mHandle) == 0) ? true : false;
#endif
}
/// Unlock the mutex.
/// If any threads are waiting for the lock on this mutex, one of them will
/// be unblocked.
inline void unlock()
{
#if defined(_TTHREAD_WIN32_)
LeaveCriticalSection(&mHandle);
#else
pthread_mutex_unlock(&mHandle);
#endif
}
_TTHREAD_DISABLE_ASSIGNMENT(recursive_mutex)
private:
#if defined(_TTHREAD_WIN32_)
CRITICAL_SECTION mHandle;
#else
pthread_mutex_t mHandle;
#endif
friend class condition_variable;
};
/// Lock guard class.
/// The constructor locks the mutex, and the destructor unlocks the mutex, so
/// the mutex will automatically be unlocked when the lock guard goes out of
/// scope. Example usage:
/// @code
/// mutex m;
/// int counter;
///
/// void increment()
/// {
/// lock_guard<mutex> guard(m);
/// ++ counter;
/// }
/// @endcode
template <class T>
class lock_guard {
public:
typedef T mutex_type;
lock_guard() : mMutex(0) {}
/// The constructor locks the mutex.
explicit lock_guard(mutex_type &aMutex)
{
mMutex = &aMutex;
mMutex->lock();
}
/// The destructor unlocks the mutex.
~lock_guard()
{
if(mMutex)
mMutex->unlock();
}
private:
mutex_type * mMutex;
};
/// Condition variable class.
/// This is a signalling object for synchronizing the execution flow for
/// several threads. Example usage:
/// @code
/// // Shared data and associated mutex and condition variable objects
/// int count;
/// mutex m;
/// condition_variable cond;
///
/// // Wait for the counter to reach a certain number
/// void wait_counter(int targetCount)
/// {
/// lock_guard<mutex> guard(m);
/// while(count < targetCount)
/// cond.wait(m);
/// }
///
/// // Increment the counter, and notify waiting threads
/// void increment()
/// {
/// lock_guard<mutex> guard(m);
/// ++ count;
/// cond.notify_all();
/// }
/// @endcode
class condition_variable {
public:
/// Constructor.
#if defined(_TTHREAD_WIN32_)
condition_variable();
#else
condition_variable()
{
pthread_cond_init(&mHandle, NULL);
}
#endif
/// Destructor.
#if defined(_TTHREAD_WIN32_)
~condition_variable();
#else
~condition_variable()
{
pthread_cond_destroy(&mHandle);
}
#endif
/// Wait for the condition.
/// The function will block the calling thread until the condition variable
/// is woken by @c notify_one(), @c notify_all() or a spurious wake up.
/// @param[in] aMutex A mutex that will be unlocked when the wait operation
/// starts, an locked again as soon as the wait operation is finished.
template <class _mutexT>
inline void wait(_mutexT &aMutex)
{
#if defined(_TTHREAD_WIN32_)
// Increment number of waiters
EnterCriticalSection(&mWaitersCountLock);
++ mWaitersCount;
LeaveCriticalSection(&mWaitersCountLock);
// Release the mutex while waiting for the condition (will decrease
// the number of waiters when done)...
aMutex.unlock();
_wait();
aMutex.lock();
#else
pthread_cond_wait(&mHandle, &aMutex.mHandle);
#endif
}
/// Notify one thread that is waiting for the condition.
/// If at least one thread is blocked waiting for this condition variable,
/// one will be woken up.
/// @note Only threads that started waiting prior to this call will be
/// woken up.
#if defined(_TTHREAD_WIN32_)
void notify_one();
#else
inline void notify_one()
{
pthread_cond_signal(&mHandle);
}
#endif
/// Notify all threads that are waiting for the condition.
/// All threads that are blocked waiting for this condition variable will
/// be woken up.
/// @note Only threads that started waiting prior to this call will be
/// woken up.
#if defined(_TTHREAD_WIN32_)
void notify_all();
#else
inline void notify_all()
{
pthread_cond_broadcast(&mHandle);
}
#endif
_TTHREAD_DISABLE_ASSIGNMENT(condition_variable)
private:
#if defined(_TTHREAD_WIN32_)
void _wait();
HANDLE mEvents[2]; ///< Signal and broadcast event HANDLEs.
unsigned int mWaitersCount; ///< Count of the number of waiters.
CRITICAL_SECTION mWaitersCountLock; ///< Serialize access to mWaitersCount.
#else
pthread_cond_t mHandle;
#endif
};
/// Thread class.
class thread {
public:
#if defined(_TTHREAD_WIN32_)
typedef HANDLE native_handle_type;
#else
typedef pthread_t native_handle_type;
#endif
class id;
/// Default constructor.
/// Construct a @c thread object without an associated thread of execution
/// (i.e. non-joinable).
thread() : mHandle(0), mNotAThread(true)
#if defined(_TTHREAD_WIN32_)
, mWin32ThreadID(0)
#endif
{}
/// Thread starting constructor.
/// Construct a @c thread object with a new thread of execution.
/// @param[in] aFunction A function pointer to a function of type:
/// <tt>void fun(void * arg)</tt>
/// @param[in] aArg Argument to the thread function.
/// @note This constructor is not fully compatible with the standard C++
/// thread class. It is more similar to the pthread_create() (POSIX) and
/// CreateThread() (Windows) functions.
thread(void (*aFunction)(void *), void * aArg);
/// Destructor.
/// @note If the thread is joinable upon destruction, @c std::terminate()
/// will be called, which terminates the process. It is always wise to do
/// @c join() before deleting a thread object.
~thread();
/// Wait for the thread to finish (join execution flows).
/// After calling @c join(), the thread object is no longer associated with
/// a thread of execution (i.e. it is not joinable, and you may not join
/// with it nor detach from it).
void join();
/// Check if the thread is joinable.
/// A thread object is joinable if it has an associated thread of execution.
bool joinable() const;
/// Detach from the thread.
/// After calling @c detach(), the thread object is no longer assicated with
/// a thread of execution (i.e. it is not joinable). The thread continues
/// execution without the calling thread blocking, and when the thread
/// ends execution, any owned resources are released.
void detach();
/// Return the thread ID of a thread object.
id get_id() const;
/// Get the native handle for this thread.
/// @note Under Windows, this is a @c HANDLE, and under POSIX systems, this
/// is a @c pthread_t.
inline native_handle_type native_handle()
{
return mHandle;
}
/// Determine the number of threads which can possibly execute concurrently.
/// This function is useful for determining the optimal number of threads to
/// use for a task.
/// @return The number of hardware thread contexts in the system.
/// @note If this value is not defined, the function returns zero (0).
static unsigned hardware_concurrency();
_TTHREAD_DISABLE_ASSIGNMENT(thread)
private:
native_handle_type mHandle; ///< Thread handle.
mutable mutex mDataMutex; ///< Serializer for access to the thread private data.
bool mNotAThread; ///< True if this object is not a thread of execution.
#if defined(_TTHREAD_WIN32_)
unsigned int mWin32ThreadID; ///< Unique thread ID (filled out by _beginthreadex).
#endif
// This is the internal thread wrapper function.
#if defined(_TTHREAD_WIN32_)
static unsigned WINAPI wrapper_function(void * aArg);
#else
static void * wrapper_function(void * aArg);
#endif
};
/// Thread ID.
/// The thread ID is a unique identifier for each thread.
/// @see thread::get_id()
class thread::id {
public:
/// Default constructor.
/// The default constructed ID is that of thread without a thread of
/// execution.
id() : mId(0) {};
id(unsigned long int aId) : mId(aId) {};
id(const id& aId) : mId(aId.mId) {};
inline id & operator=(const id &aId)
{
mId = aId.mId;
return *this;
}
inline friend bool operator==(const id &aId1, const id &aId2)
{
return (aId1.mId == aId2.mId);
}
inline friend bool operator!=(const id &aId1, const id &aId2)
{
return (aId1.mId != aId2.mId);
}
inline friend bool operator<=(const id &aId1, const id &aId2)
{
return (aId1.mId <= aId2.mId);
}
inline friend bool operator<(const id &aId1, const id &aId2)
{
return (aId1.mId < aId2.mId);
}
inline friend bool operator>=(const id &aId1, const id &aId2)
{
return (aId1.mId >= aId2.mId);
}
inline friend bool operator>(const id &aId1, const id &aId2)
{
return (aId1.mId > aId2.mId);
}
inline friend std::ostream& operator <<(std::ostream &os, const id &obj)
{
os << obj.mId;
return os;
}
private:
unsigned long int mId;
};
// Related to <ratio> - minimal to be able to support chrono.
typedef long long __intmax_t;
/// Minimal implementation of the @c ratio class. This class provides enough
/// functionality to implement some basic @c chrono classes.
template <__intmax_t N, __intmax_t D = 1> class ratio {
public:
static double _as_double() { return double(N) / double(D); }
};
/// Minimal implementation of the @c chrono namespace.
/// The @c chrono namespace provides types for specifying time intervals.
namespace chrono {
/// Duration template class. This class provides enough functionality to
/// implement @c this_thread::sleep_for().
template <class _Rep, class _Period = ratio<1> > class duration {
private:
_Rep rep_;
public:
typedef _Rep rep;
typedef _Period period;
/// Construct a duration object with the given duration.
template <class _Rep2>
explicit duration(const _Rep2& r) : rep_(r) {};
/// Return the value of the duration object.
rep count() const
{
return rep_;
}
};
// Standard duration types.
typedef duration<__intmax_t, ratio<1, 1000000000> > nanoseconds; ///< Duration with the unit nanoseconds.
typedef duration<__intmax_t, ratio<1, 1000000> > microseconds; ///< Duration with the unit microseconds.
typedef duration<__intmax_t, ratio<1, 1000> > milliseconds; ///< Duration with the unit milliseconds.
typedef duration<__intmax_t> seconds; ///< Duration with the unit seconds.
typedef duration<__intmax_t, ratio<60> > minutes; ///< Duration with the unit minutes.
typedef duration<__intmax_t, ratio<3600> > hours; ///< Duration with the unit hours.
}
/// The namespace @c this_thread provides methods for dealing with the
/// calling thread.
namespace this_thread {
/// Return the thread ID of the calling thread.
thread::id get_id();
/// Yield execution to another thread.
/// Offers the operating system the opportunity to schedule another thread
/// that is ready to run on the current processor.
inline void yield()
{
#if defined(_TTHREAD_WIN32_)
Sleep(0);
#else
sched_yield();
#endif
}
/// Blocks the calling thread for a period of time.
/// @param[in] aTime Minimum time to put the thread to sleep.
/// Example usage:
/// @code
/// // Sleep for 100 milliseconds
/// this_thread::sleep_for(chrono::milliseconds(100));
/// @endcode
/// @note Supported duration types are: nanoseconds, microseconds,
/// milliseconds, seconds, minutes and hours.
template <class _Rep, class _Period> void sleep_for(const chrono::duration<_Rep, _Period>& aTime)
{
#if defined(_TTHREAD_WIN32_)
Sleep(int(double(aTime.count()) * (1000.0 * _Period::_as_double()) + 0.5));
#else
usleep(int(double(aTime.count()) * (1000000.0 * _Period::_as_double()) + 0.5));
#endif
}
}
}
// Define/macro cleanup
#undef _TTHREAD_DISABLE_ASSIGNMENT
#endif // _TINYTHREAD_H_

@ -319,12 +319,12 @@ if(UNIX)
endif() endif()
if(APPLE) if(APPLE)
set(PROJECT_LIBS dl dfhack-md5 ${DFHACK_TINYXML} dfhack-tinythread) set(PROJECT_LIBS dl dfhack-md5 ${DFHACK_TINYXML})
elseif(UNIX) elseif(UNIX)
set(PROJECT_LIBS rt dl dfhack-md5 ${DFHACK_TINYXML} dfhack-tinythread) set(PROJECT_LIBS rt dl dfhack-md5 ${DFHACK_TINYXML})
else(WIN32) else(WIN32)
# FIXME: do we really need psapi? # FIXME: do we really need psapi?
set(PROJECT_LIBS psapi dfhack-md5 ${DFHACK_TINYXML} dfhack-tinythread) set(PROJECT_LIBS psapi dfhack-md5 ${DFHACK_TINYXML})
endif() endif()
set(VERSION_SRCS DFHackVersion.cpp) set(VERSION_SRCS DFHackVersion.cpp)

@ -55,9 +55,6 @@ POSSIBILITY OF SUCH DAMAGE.
using namespace std; using namespace std;
using namespace DFHack; using namespace DFHack;
#include "tinythread.h"
using namespace tthread;
bool color_ostream::log_errors_to_stderr = false; bool color_ostream::log_errors_to_stderr = false;
void color_ostream::flush_buffer(bool flush) void color_ostream::flush_buffer(bool flush)

@ -79,9 +79,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "Hooks.h" #include "Hooks.h"
using namespace DFHack; using namespace DFHack;
#include "tinythread.h"
using namespace tthread;
static int isUnsupportedTerm(void) static int isUnsupportedTerm(void)
{ {
static const char *unsupported_term[] = {"dumb","cons25",NULL}; static const char *unsupported_term[] = {"dumb","cons25",NULL};
@ -403,7 +400,7 @@ namespace DFHack
prompt_refresh(); prompt_refresh();
} }
/// A simple line edit (raw mode) /// A simple line edit (raw mode)
int lineedit(const std::string& prompt, std::string& output, recursive_mutex * lock, CommandHistory & ch) int lineedit(const std::string& prompt, std::string& output, std::recursive_mutex * lock, CommandHistory & ch)
{ {
if(state == con_lineedit) if(state == con_lineedit)
return Console::FAILURE; return Console::FAILURE;
@ -518,7 +515,7 @@ namespace DFHack
if (::write(STDIN_FILENO,seq,strlen(seq)) == -1) return; if (::write(STDIN_FILENO,seq,strlen(seq)) == -1) return;
} }
int prompt_loop(recursive_mutex * lock, CommandHistory & history) int prompt_loop(std::recursive_mutex * lock, CommandHistory & history)
{ {
int fd = STDIN_FILENO; int fd = STDIN_FILENO;
size_t plen = prompt.size(); size_t plen = prompt.size();
@ -841,7 +838,7 @@ Console::Console()
d = 0; d = 0;
inited = false; inited = false;
// we can't create the mutex at this time. the SDL functions aren't hooked yet. // we can't create the mutex at this time. the SDL functions aren't hooked yet.
wlock = new recursive_mutex(); wlock = new std::recursive_mutex();
} }
Console::~Console() Console::~Console()
{ {
@ -890,7 +887,7 @@ bool Console::shutdown(void)
if(!d) if(!d)
return true; return true;
d->reset_color(); d->reset_color();
lock_guard <recursive_mutex> g(*wlock); std::lock_guard<std::recursive_mutex> lock{*wlock};
close(d->exit_pipe[1]); close(d->exit_pipe[1]);
if (d->state != Private::con_lineedit) if (d->state != Private::con_lineedit)
inited = false; inited = false;
@ -917,14 +914,14 @@ void Console::end_batch()
void Console::flush_proxy() void Console::flush_proxy()
{ {
lock_guard <recursive_mutex> g(*wlock); std::lock_guard<std::recursive_mutex> lock{*wlock};
if (inited) if (inited)
d->flush(); d->flush();
} }
void Console::add_text(color_value color, const std::string &text) void Console::add_text(color_value color, const std::string &text)
{ {
lock_guard <recursive_mutex> g(*wlock); std::lock_guard<std::recursive_mutex> lock{*wlock};
if (inited) if (inited)
d->print_text(color, text); d->print_text(color, text);
else else
@ -933,7 +930,7 @@ void Console::add_text(color_value color, const std::string &text)
int Console::get_columns(void) int Console::get_columns(void)
{ {
lock_guard <recursive_mutex> g(*wlock); std::lock_guard<std::recursive_mutex> lock{*wlock};
int ret = Console::FAILURE; int ret = Console::FAILURE;
if(inited) if(inited)
ret = d->get_columns(); ret = d->get_columns();
@ -942,7 +939,7 @@ int Console::get_columns(void)
int Console::get_rows(void) int Console::get_rows(void)
{ {
lock_guard <recursive_mutex> g(*wlock); std::lock_guard<std::recursive_mutex> lock{*wlock};
int ret = Console::FAILURE; int ret = Console::FAILURE;
if(inited) if(inited)
ret = d->get_rows(); ret = d->get_rows();
@ -951,28 +948,28 @@ int Console::get_rows(void)
void Console::clear() void Console::clear()
{ {
lock_guard <recursive_mutex> g(*wlock); std::lock_guard<std::recursive_mutex> lock{*wlock};
if(inited) if(inited)
d->clear(); d->clear();
} }
void Console::gotoxy(int x, int y) void Console::gotoxy(int x, int y)
{ {
lock_guard <recursive_mutex> g(*wlock); std::lock_guard<std::recursive_mutex> lock{*wlock};
if(inited) if(inited)
d->gotoxy(x,y); d->gotoxy(x,y);
} }
void Console::cursor(bool enable) void Console::cursor(bool enable)
{ {
lock_guard <recursive_mutex> g(*wlock); std::lock_guard<std::recursive_mutex> lock{*wlock};
if(inited) if(inited)
d->cursor(enable); d->cursor(enable);
} }
int Console::lineedit(const std::string & prompt, std::string & output, CommandHistory & ch) int Console::lineedit(const std::string & prompt, std::string & output, CommandHistory & ch)
{ {
lock_guard <recursive_mutex> g(*wlock); std::lock_guard<std::recursive_mutex> lock{*wlock};
int ret = Console::SHUTDOWN; int ret = Console::SHUTDOWN;
if(inited) { if(inited) {
ret = d->lineedit(prompt,output,wlock,ch); ret = d->lineedit(prompt,output,wlock,ch);

@ -58,9 +58,6 @@ POSSIBILITY OF SUCH DAMAGE.
#include <deque> #include <deque>
using namespace DFHack; using namespace DFHack;
#include "tinythread.h"
using namespace tthread;
// FIXME: maybe make configurable with an ini option? // FIXME: maybe make configurable with an ini option?
#define MAX_CONSOLE_LINES 999 #define MAX_CONSOLE_LINES 999
@ -262,7 +259,7 @@ namespace DFHack
SetConsoleCursorPosition(console_out, inf.dwCursorPosition); SetConsoleCursorPosition(console_out, inf.dwCursorPosition);
} }
int prompt_loop(recursive_mutex * lock, CommandHistory & history) int prompt_loop(std::recursive_mutex * lock, CommandHistory & history)
{ {
raw_buffer.clear(); // make sure the buffer is empty! raw_buffer.clear(); // make sure the buffer is empty!
size_t plen = prompt.size(); size_t plen = prompt.size();
@ -374,7 +371,7 @@ namespace DFHack
} }
} }
} }
int lineedit(const std::string & prompt, std::string & output, recursive_mutex * lock, CommandHistory & ch) int lineedit(const std::string & prompt, std::string & output, std::recursive_mutex * lock, CommandHistory & ch)
{ {
if(state == con_lineedit) if(state == con_lineedit)
return Console::FAILURE; return Console::FAILURE;
@ -472,7 +469,7 @@ bool Console::init(bool)
// Allocate a console! // Allocate a console!
AllocConsole(); AllocConsole();
d->ConsoleWindow = GetConsoleWindow(); d->ConsoleWindow = GetConsoleWindow();
wlock = new recursive_mutex(); wlock = new std::recursive_mutex();
HMENU hm = GetSystemMenu(d->ConsoleWindow,false); HMENU hm = GetSystemMenu(d->ConsoleWindow,false);
DeleteMenu(hm, SC_CLOSE, MF_BYCOMMAND); DeleteMenu(hm, SC_CLOSE, MF_BYCOMMAND);
@ -514,7 +511,7 @@ bool Console::init(bool)
// FIXME: looks awfully empty, doesn't it? // FIXME: looks awfully empty, doesn't it?
bool Console::shutdown(void) bool Console::shutdown(void)
{ {
lock_guard <recursive_mutex> g(*wlock); std::lock_guard<std::recursive_mutex> lock{*wlock};
FreeConsole(); FreeConsole();
inited = false; inited = false;
return true; return true;
@ -540,21 +537,21 @@ void Console::end_batch()
void Console::flush_proxy() void Console::flush_proxy()
{ {
lock_guard <recursive_mutex> g(*wlock); std::lock_guard<std::recursive_mutex> lock{*wlock};
if (inited) if (inited)
d->flush(); d->flush();
} }
void Console::add_text(color_value color, const std::string &text) void Console::add_text(color_value color, const std::string &text)
{ {
lock_guard <recursive_mutex> g(*wlock); std::lock_guard<std::recursive_mutex> lock{*wlock};
if (inited) if (inited)
d->print_text(color, text); d->print_text(color, text);
} }
int Console::get_columns(void) int Console::get_columns(void)
{ {
lock_guard <recursive_mutex> g(*wlock); std::lock_guard<std::recursive_mutex> lock{*wlock};
int ret = -1; int ret = -1;
if(inited) if(inited)
ret = d->get_columns(); ret = d->get_columns();
@ -563,7 +560,7 @@ int Console::get_columns(void)
int Console::get_rows(void) int Console::get_rows(void)
{ {
lock_guard <recursive_mutex> g(*wlock); std::lock_guard<std::recursive_mutex> lock{*wlock};
int ret = -1; int ret = -1;
if(inited) if(inited)
ret = d->get_rows(); ret = d->get_rows();
@ -572,21 +569,21 @@ int Console::get_rows(void)
void Console::clear() void Console::clear()
{ {
lock_guard <recursive_mutex> g(*wlock); std::lock_guard<std::recursive_mutex> lock{*wlock};
if(inited) if(inited)
d->clear(); d->clear();
} }
void Console::gotoxy(int x, int y) void Console::gotoxy(int x, int y)
{ {
lock_guard <recursive_mutex> g(*wlock); std::lock_guard<std::recursive_mutex> lock{*wlock};
if(inited) if(inited)
d->gotoxy(x,y); d->gotoxy(x,y);
} }
void Console::cursor(bool enable) void Console::cursor(bool enable)
{ {
lock_guard <recursive_mutex> g(*wlock); std::lock_guard<std::recursive_mutex> lock{*wlock};
if(inited) if(inited)
d->cursor(enable); d->cursor(enable);
} }

@ -31,7 +31,6 @@ distribution.
#include "MemAccess.h" #include "MemAccess.h"
#include "Core.h" #include "Core.h"
#include "VersionInfo.h" #include "VersionInfo.h"
#include "tinythread.h"
// must be last due to MS stupidity // must be last due to MS stupidity
#include "DataDefs.h" #include "DataDefs.h"
#include "DataIdentity.h" #include "DataIdentity.h"
@ -118,12 +117,12 @@ std::string compound_identity::getFullName()
return getName(); return getName();
} }
static tthread::mutex *known_mutex = NULL; static std::mutex *known_mutex = NULL;
void compound_identity::Init(Core *core) void compound_identity::Init(Core *core)
{ {
if (!known_mutex) if (!known_mutex)
known_mutex = new tthread::mutex(); known_mutex = new std::mutex();
// This cannot be done in the constructors, because // This cannot be done in the constructors, because
// they are called in an undefined order. // they are called in an undefined order.
@ -310,7 +309,7 @@ virtual_identity *virtual_identity::find(void *vtable)
// Actually, a reader/writer lock would be sufficient, // Actually, a reader/writer lock would be sufficient,
// since the table is only written once per class. // since the table is only written once per class.
tthread::lock_guard<tthread::mutex> lock(*known_mutex); std::lock_guard<std::mutex> lock(*known_mutex);
std::map<void*, virtual_identity*>::iterator it = known.find(vtable); std::map<void*, virtual_identity*>::iterator it = known.find(vtable);

@ -33,14 +33,12 @@ distribution.
#include "Core.h" #include "Core.h"
#include "Error.h" #include "Error.h"
#include "VersionInfo.h" #include "VersionInfo.h"
#include "tinythread.h"
// must be last due to MS stupidity // must be last due to MS stupidity
#include "DataDefs.h" #include "DataDefs.h"
#include "DataIdentity.h" #include "DataIdentity.h"
#include "DataFuncs.h" #include "DataFuncs.h"
#include "DFHackVersion.h" #include "DFHackVersion.h"
#include "PluginManager.h" #include "PluginManager.h"
#include "tinythread.h"
#include "md5wrapper.h" #include "md5wrapper.h"
#include "modules/Buildings.h" #include "modules/Buildings.h"
@ -3703,7 +3701,7 @@ static int internal_getCommandDescription(lua_State *L)
static int internal_threadid(lua_State *L) static int internal_threadid(lua_State *L)
{ {
std::stringstream ss; std::stringstream ss;
ss << tthread::this_thread::get_id(); ss << std::this_thread::get_id();
int i; int i;
ss >> i; ss >> i;
lua_pushinteger(L, i); lua_pushinteger(L, i);

@ -32,7 +32,6 @@ distribution.
#include "MemAccess.h" #include "MemAccess.h"
#include "Core.h" #include "Core.h"
#include "VersionInfo.h" #include "VersionInfo.h"
#include "tinythread.h"
// must be last due to MS stupidity // must be last due to MS stupidity
#include "DataDefs.h" #include "DataDefs.h"
#include "DataIdentity.h" #include "DataIdentity.h"

@ -32,7 +32,6 @@ distribution.
#include "Core.h" #include "Core.h"
#include "Error.h" #include "Error.h"
#include "VersionInfo.h" #include "VersionInfo.h"
#include "tinythread.h"
// must be last due to MS stupidity // must be last due to MS stupidity
#include "DataDefs.h" #include "DataDefs.h"
#include "DataIdentity.h" #include "DataIdentity.h"

@ -32,7 +32,6 @@ distribution.
#include "MemAccess.h" #include "MemAccess.h"
#include "Core.h" #include "Core.h"
#include "VersionInfo.h" #include "VersionInfo.h"
#include "tinythread.h"
// must be last due to MS stupidity // must be last due to MS stupidity
#include "DataDefs.h" #include "DataDefs.h"
#include "DataIdentity.h" #include "DataIdentity.h"

@ -34,8 +34,6 @@ distribution.
#include "Hooks.h" #include "Hooks.h"
#include <stdio.h> #include <stdio.h>
#include "tinythread.h"
/* /*
* Plugin loading functions * Plugin loading functions
*/ */

@ -43,22 +43,14 @@ distribution.
using namespace DFHack; using namespace DFHack;
#include <condition_variable>
#include <string> #include <string>
#include <vector> #include <vector>
#include <map> #include <map>
using namespace std; using namespace std;
#include "tinythread.h"
#include <assert.h> #include <assert.h>
#define MUTEX_GUARD(lock) auto lock_##__LINE__ = make_mutex_guard(lock);
template <typename T>
tthread::lock_guard<T> make_mutex_guard (T *mutex)
{
return tthread::lock_guard<T>(*mutex);
}
#if defined(_LINUX) #if defined(_LINUX)
static const string plugin_suffix = ".plug.so"; static const string plugin_suffix = ".plug.so";
#elif defined(_DARWIN) #elif defined(_DARWIN)
@ -82,8 +74,8 @@ struct Plugin::RefLock
RefLock() RefLock()
{ {
refcount = 0; refcount = 0;
wakeup = new tthread::condition_variable(); wakeup = new std::condition_variable();
mut = new tthread::mutex(); mut = new std::mutex();
} }
~RefLock() ~RefLock()
{ {
@ -113,13 +105,14 @@ struct Plugin::RefLock
} }
void wait() void wait()
{ {
std::unique_lock<std::mutex> lock{*mut, std::defer_lock};
while(refcount) while(refcount)
{ {
wakeup->wait(*mut); wakeup->wait(lock);
} }
} }
tthread::condition_variable * wakeup; std::condition_variable * wakeup;
tthread::mutex * mut; std::mutex * mut;
int refcount; int refcount;
}; };
@ -822,8 +815,8 @@ void Plugin::push_function(lua_State *state, LuaFunction *fn)
PluginManager::PluginManager(Core * core) : core(core) PluginManager::PluginManager(Core * core) : core(core)
{ {
plugin_mutex = new tthread::recursive_mutex(); plugin_mutex = new std::recursive_mutex();
cmdlist_mutex = new tthread::mutex(); cmdlist_mutex = new std::mutex();
} }
PluginManager::~PluginManager() PluginManager::~PluginManager()
@ -898,7 +891,7 @@ vector<string> PluginManager::listPlugins()
void PluginManager::refresh() void PluginManager::refresh()
{ {
MUTEX_GUARD(plugin_mutex); lock_guard<std::recursive_mutex> lock{*plugin_mutex};
auto files = listPlugins(); auto files = listPlugins();
for (auto f = files.begin(); f != files.end(); ++f) for (auto f = files.begin(); f != files.end(); ++f)
{ {
@ -909,7 +902,7 @@ void PluginManager::refresh()
bool PluginManager::load (const string &name) bool PluginManager::load (const string &name)
{ {
MUTEX_GUARD(plugin_mutex); lock_guard<std::recursive_mutex> lock{*plugin_mutex};
if (!(*this)[name] && !addPlugin(name)) if (!(*this)[name] && !addPlugin(name))
return false; return false;
Plugin *p = (*this)[name]; Plugin *p = (*this)[name];
@ -923,7 +916,7 @@ bool PluginManager::load (const string &name)
bool PluginManager::loadAll() bool PluginManager::loadAll()
{ {
MUTEX_GUARD(plugin_mutex); lock_guard<std::recursive_mutex> lock{*plugin_mutex};
auto files = listPlugins(); auto files = listPlugins();
bool ok = true; bool ok = true;
// load all plugins in hack/plugins // load all plugins in hack/plugins
@ -937,7 +930,7 @@ bool PluginManager::loadAll()
bool PluginManager::unload (const string &name) bool PluginManager::unload (const string &name)
{ {
MUTEX_GUARD(plugin_mutex); lock_guard<std::recursive_mutex> lock{*plugin_mutex};
if (!(*this)[name]) if (!(*this)[name])
{ {
Core::printerr("Plugin does not exist: %s\n", name.c_str()); Core::printerr("Plugin does not exist: %s\n", name.c_str());
@ -948,7 +941,7 @@ bool PluginManager::unload (const string &name)
bool PluginManager::unloadAll() bool PluginManager::unloadAll()
{ {
MUTEX_GUARD(plugin_mutex); lock_guard<std::recursive_mutex> lock{*plugin_mutex};
bool ok = true; bool ok = true;
// only try to unload plugins that are in all_plugins // only try to unload plugins that are in all_plugins
for (auto it = begin(); it != end(); ++it) for (auto it = begin(); it != end(); ++it)
@ -963,7 +956,7 @@ bool PluginManager::reload (const string &name)
{ {
// equivalent to "unload(name); load(name);" if plugin is recognized, // equivalent to "unload(name); load(name);" if plugin is recognized,
// "load(name);" otherwise // "load(name);" otherwise
MUTEX_GUARD(plugin_mutex); lock_guard<std::recursive_mutex> lock{*plugin_mutex};
if (!(*this)[name]) if (!(*this)[name])
return load(name); return load(name);
if (!unload(name)) if (!unload(name))
@ -973,7 +966,7 @@ bool PluginManager::reload (const string &name)
bool PluginManager::reloadAll() bool PluginManager::reloadAll()
{ {
MUTEX_GUARD(plugin_mutex); lock_guard<std::recursive_mutex> lock{*plugin_mutex};
bool ok = true; bool ok = true;
if (!unloadAll()) if (!unloadAll())
ok = false; ok = false;
@ -984,7 +977,7 @@ bool PluginManager::reloadAll()
Plugin *PluginManager::getPluginByCommand(const std::string &command) Plugin *PluginManager::getPluginByCommand(const std::string &command)
{ {
tthread::lock_guard<tthread::mutex> lock(*cmdlist_mutex); lock_guard<std::mutex> lock{*cmdlist_mutex};
map <string, Plugin *>::iterator iter = command_map.find(command); map <string, Plugin *>::iterator iter = command_map.find(command);
if (iter != command_map.end()) if (iter != command_map.end())
return iter->second; return iter->second;
@ -1019,7 +1012,7 @@ void PluginManager::OnStateChange(color_ostream &out, state_change_event event)
void PluginManager::registerCommands( Plugin * p ) void PluginManager::registerCommands( Plugin * p )
{ {
cmdlist_mutex->lock(); lock_guard<std::mutex> lock{*cmdlist_mutex};
vector <PluginCommand> & cmds = p->commands; vector <PluginCommand> & cmds = p->commands;
for (size_t i = 0; i < cmds.size();i++) for (size_t i = 0; i < cmds.size();i++)
{ {
@ -1032,18 +1025,16 @@ void PluginManager::registerCommands( Plugin * p )
} }
command_map[name] = p; command_map[name] = p;
} }
cmdlist_mutex->unlock();
} }
void PluginManager::unregisterCommands( Plugin * p ) void PluginManager::unregisterCommands( Plugin * p )
{ {
cmdlist_mutex->lock(); lock_guard<std::mutex> lock{*cmdlist_mutex};
vector <PluginCommand> & cmds = p->commands; vector <PluginCommand> & cmds = p->commands;
for(size_t i = 0; i < cmds.size();i++) for(size_t i = 0; i < cmds.size();i++)
{ {
command_map.erase(cmds[i].name); command_map.erase(cmds[i].name);
} }
cmdlist_mutex->unlock();
} }
void PluginManager::doSaveData(color_ostream &out) void PluginManager::doSaveData(color_ostream &out)
@ -1070,7 +1061,7 @@ void PluginManager::doLoadData(color_ostream &out)
Plugin *PluginManager::operator[] (std::string name) Plugin *PluginManager::operator[] (std::string name)
{ {
MUTEX_GUARD(plugin_mutex); lock_guard<std::recursive_mutex> lock{*plugin_mutex};
if (all_plugins.find(name) == all_plugins.end()) if (all_plugins.find(name) == all_plugins.end())
{ {
if (Filesystem::isfile(getPluginPath(name))) if (Filesystem::isfile(getPluginPath(name)))

@ -56,10 +56,8 @@ POSSIBILITY OF SUCH DAMAGE.
#include <memory> #include <memory>
#include "json/json.h" #include "json/json.h"
#include "tinythread.h"
using namespace DFHack; using namespace DFHack;
using namespace tthread;
using dfproto::CoreTextNotification; using dfproto::CoreTextNotification;

@ -31,15 +31,10 @@ distribution.
#include <fstream> #include <fstream>
#include <assert.h> #include <assert.h>
#include <iostream> #include <iostream>
#include <mutex>
#include <string> #include <string>
#include <vector> #include <vector>
namespace tthread
{
class mutex;
class recursive_mutex;
class condition_variable;
class thread;
}
namespace DFHack namespace DFHack
{ {
class CommandHistory class CommandHistory
@ -176,7 +171,7 @@ namespace DFHack
bool show(); bool show();
private: private:
Private * d; Private * d;
tthread::recursive_mutex * wlock; std::recursive_mutex * wlock;
std::atomic<bool> inited; std::atomic<bool> inited;
}; };
} }

@ -29,6 +29,7 @@ distribution.
#include "ColorText.h" #include "ColorText.h"
#include "MiscUtils.h" #include "MiscUtils.h"
#include <map> #include <map>
#include <mutex>
#include <string> #include <string>
#include <vector> #include <vector>
@ -37,11 +38,6 @@ distribution.
typedef struct lua_State lua_State; typedef struct lua_State lua_State;
namespace tthread
{
class mutex;
class condition_variable;
}
namespace df namespace df
{ {
struct viewscreen; struct viewscreen;
@ -280,8 +276,8 @@ namespace DFHack
private: private:
Core *core; Core *core;
bool addPlugin(std::string name); bool addPlugin(std::string name);
tthread::recursive_mutex * plugin_mutex; std::recursive_mutex * plugin_mutex;
tthread::mutex * cmdlist_mutex; std::mutex * cmdlist_mutex;
std::map <std::string, Plugin*> command_map; std::map <std::string, Plugin*> command_map;
std::map <std::string, Plugin*> all_plugins; std::map <std::string, Plugin*> all_plugins;
std::string plugin_path; std::string plugin_path;

@ -131,7 +131,7 @@ if(BUILD_SUPPORTED)
#dfhack_plugin(jobutils jobutils.cpp) #dfhack_plugin(jobutils jobutils.cpp)
dfhack_plugin(lair lair.cpp) dfhack_plugin(lair lair.cpp)
dfhack_plugin(liquids liquids.cpp Brushes.h LINK_LIBRARIES lua) dfhack_plugin(liquids liquids.cpp Brushes.h LINK_LIBRARIES lua)
dfhack_plugin(luasocket luasocket.cpp LINK_LIBRARIES clsocket lua dfhack-tinythread) dfhack_plugin(luasocket luasocket.cpp LINK_LIBRARIES clsocket lua)
dfhack_plugin(logistics logistics.cpp LINK_LIBRARIES lua) dfhack_plugin(logistics logistics.cpp LINK_LIBRARIES lua)
#dfhack_plugin(manipulator manipulator.cpp) #dfhack_plugin(manipulator manipulator.cpp)
#dfhack_plugin(map-render map-render.cpp LINK_LIBRARIES lua) #dfhack_plugin(map-render map-render.cpp LINK_LIBRARIES lua)

@ -3,7 +3,7 @@
#include "PluginManager.h" #include "PluginManager.h"
#include "MemAccess.h" #include "MemAccess.h"
#include "MiscUtils.h" #include "MiscUtils.h"
#include <tinythread.h> //not sure if correct #include <mutex>
#include <string> #include <string>
#include <vector> #include <vector>
#include <sstream> #include <sstream>
@ -15,7 +15,7 @@ using std::string;
using namespace DFHack; using namespace DFHack;
uint64_t timeLast=0; uint64_t timeLast=0;
static tthread::mutex* mymutex=0; static std::mutex* mymutex=0;
DFHACK_PLUGIN_IS_ENABLED(is_enabled); DFHACK_PLUGIN_IS_ENABLED(is_enabled);
@ -40,7 +40,7 @@ DFhackCExport command_result plugin_init (color_ostream &out, std::vector <Plugi
{ {
commands.push_back(PluginCommand("memview","Shows DF memory in real time.",memview,false,"Shows memory in real time.\nParams: adrr length refresh_rate. If addr==0 then stop viewing.")); commands.push_back(PluginCommand("memview","Shows DF memory in real time.",memview,false,"Shows memory in real time.\nParams: adrr length refresh_rate. If addr==0 then stop viewing."));
memdata.state=STATE_OFF; memdata.state=STATE_OFF;
mymutex=new tthread::mutex; mymutex=new std::mutex;
return CR_OK; return CR_OK;
} }
size_t convert(const std::string& p,bool ishex=false) size_t convert(const std::string& p,bool ishex=false)

@ -16,6 +16,6 @@ set_source_files_properties(${PROJECT_HDRS} PROPERTIES HEADER_FILE_ONLY TRUE)
list(APPEND PROJECT_SRCS ${PROJECT_HDRS}) list(APPEND PROJECT_SRCS ${PROJECT_HDRS})
# this makes sure all the stuff is put in proper places and linked to dfhack # this makes sure all the stuff is put in proper places and linked to dfhack
dfhack_plugin(rendermax ${PROJECT_SRCS} LINK_LIBRARIES lua dfhack-tinythread) dfhack_plugin(rendermax ${PROJECT_SRCS} LINK_LIBRARIES lua)
install(FILES rendermax.lua install(FILES rendermax.lua
DESTINATION ${DFHACK_DATA_DESTINATION}/raw) DESTINATION ${DFHACK_DATA_DESTINATION}/raw)

@ -5,8 +5,6 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include "tinythread.h"
#include "LuaTools.h" #include "LuaTools.h"
#include "modules/Gui.h" #include "modules/Gui.h"
@ -32,7 +30,6 @@
using df::global::gps; using df::global::gps;
using namespace DFHack; using namespace DFHack;
using df::coord2d; using df::coord2d;
using namespace tthread;
const float RootTwo = 1.4142135623730950488016887242097f; const float RootTwo = 1.4142135623730950488016887242097f;
@ -108,9 +105,9 @@ lightingEngineViewscreen::lightingEngineViewscreen(renderer_light* target):light
{ {
reinit(); reinit();
defaultSettings(); defaultSettings();
int numTreads=tthread::thread::hardware_concurrency(); int numThreads=std::thread::hardware_concurrency();
if(numTreads==0)numTreads=1; if(numThreads==0)numThreads=1;
threading.start(numTreads); threading.start(numThreads);
} }
void lightingEngineViewscreen::reinit() void lightingEngineViewscreen::reinit()
@ -1261,9 +1258,9 @@ void lightThread::run()
{ {
//TODO: get area to process, and then process (by rounds): 1. occlusions, 2.sun, 3.lights(could be difficult, units/items etc...) //TODO: get area to process, and then process (by rounds): 1. occlusions, 2.sun, 3.lights(could be difficult, units/items etc...)
{//wait for occlusion (and lights) to be ready {//wait for occlusion (and lights) to be ready
tthread::lock_guard<tthread::mutex> guard(dispatch.occlusionMutex); std::unique_lock<std::mutex> guard(dispatch.occlusionMutex);
if(!dispatch.occlusionReady) if(!dispatch.occlusionReady)
dispatch.occlusionDone.wait(dispatch.occlusionMutex);//wait for work dispatch.occlusionDone.wait(guard);//wait for work
if(dispatch.unprocessed.size()==0 || !dispatch.occlusionReady) //spurious wake-up if(dispatch.unprocessed.size()==0 || !dispatch.occlusionReady) //spurious wake-up
continue; continue;
if(dispatch.occlusion.size()!=canvas.size()) //oh no somebody resized stuff if(dispatch.occlusion.size()!=canvas.size()) //oh no somebody resized stuff
@ -1272,7 +1269,7 @@ void lightThread::run()
{ //get my rectangle (any will do) { //get my rectangle (any will do)
tthread::lock_guard<tthread::mutex> guard(dispatch.unprocessedMutex); std::lock_guard<std::mutex> guard(dispatch.unprocessedMutex);
if (dispatch.unprocessed.size()==0) if (dispatch.unprocessed.size()==0)
{ {
//wtf?? why?! //wtf?? why?!
@ -1288,7 +1285,7 @@ void lightThread::run()
} }
work(); work();
{ {
tthread::lock_guard<tthread::mutex> guard(dispatch.writeLock); std::lock_guard<std::mutex> guard(dispatch.writeLock);
combine();//write it back combine();//write it back
dispatch.writeCount++; dispatch.writeCount++;
} }
@ -1399,11 +1396,11 @@ void lightThread::doLight( int x,int y )
void lightThreadDispatch::signalDoneOcclusion() void lightThreadDispatch::signalDoneOcclusion()
{ {
{ {
tthread::lock_guard<tthread::mutex> guardWrite(writeLock); std::lock_guard<std::mutex> guardWrite(writeLock);
writeCount=0; writeCount=0;
} }
tthread::lock_guard<tthread::mutex> guard1(occlusionMutex); std::lock_guard<std::mutex> guard1(occlusionMutex);
tthread::lock_guard<tthread::mutex> guard2(unprocessedMutex); std::lock_guard<std::mutex> guard2(unprocessedMutex);
while(!unprocessed.empty()) while(!unprocessed.empty())
unprocessed.pop(); unprocessed.pop();
viewPort=getMapViewport(); viewPort=getMapViewport();
@ -1465,17 +1462,17 @@ void lightThreadDispatch::start(int count)
for(int i=0;i<count;i++) for(int i=0;i<count;i++)
{ {
std::unique_ptr<lightThread> nthread(new lightThread(*this)); std::unique_ptr<lightThread> nthread(new lightThread(*this));
nthread->myThread=new tthread::thread(&threadStub,nthread.get()); nthread->myThread=new std::thread(&threadStub,nthread.get());
threadPool.push_back(std::move(nthread)); threadPool.push_back(std::move(nthread));
} }
} }
void lightThreadDispatch::waitForWrites() void lightThreadDispatch::waitForWrites()
{ {
tthread::lock_guard<tthread::mutex> guard(writeLock); std::unique_lock<std::mutex> lock(writeLock);
while(threadPool.size()>size_t(writeCount))//missed it somehow already. while(threadPool.size()>size_t(writeCount))//missed it somehow already.
{ {
writesDone.wait(writeLock); //if not, wait a bit writesDone.wait(lock); //if not, wait a bit
} }
} }

@ -1,8 +1,10 @@
#pragma once #pragma once
#include <condition_variable>
#include <memory> #include <memory>
#include <mutex> #include <mutex>
#include <stack> #include <stack>
#include <thread>
#include <tuple> #include <tuple>
#include <unordered_map> #include <unordered_map>
@ -231,18 +233,18 @@ public:
std::vector<std::unique_ptr<lightThread> > threadPool; std::vector<std::unique_ptr<lightThread> > threadPool;
std::vector<lightSource>& lights; std::vector<lightSource>& lights;
tthread::mutex occlusionMutex; std::mutex occlusionMutex;
tthread::condition_variable occlusionDone; //all threads wait for occlusion to finish std::condition_variable occlusionDone; //all threads wait for occlusion to finish
bool occlusionReady; bool occlusionReady;
tthread::mutex unprocessedMutex; std::mutex unprocessedMutex;
std::stack<DFHack::rect2d> unprocessed; //stack of parts of map where lighting is not finished std::stack<DFHack::rect2d> unprocessed; //stack of parts of map where lighting is not finished
std::vector<rgbf>& occlusion; std::vector<rgbf>& occlusion;
int& num_diffusion; int& num_diffusion;
tthread::mutex writeLock; //mutex for lightMap std::mutex writeLock; //mutex for lightMap
std::vector<rgbf>& lightMap; std::vector<rgbf>& lightMap;
tthread::condition_variable writesDone; std::condition_variable writesDone;
int writeCount; int writeCount;
lightThreadDispatch(lightingEngineViewscreen* p); lightThreadDispatch(lightingEngineViewscreen* p);
@ -263,7 +265,7 @@ class lightThread
void work(); //main light calculation function void work(); //main light calculation function
void combine(); //combine existing canvas into global lightmap void combine(); //combine existing canvas into global lightmap
public: public:
tthread::thread *myThread; std::thread *myThread;
bool isDone; //no mutex, because bool is atomic bool isDone; //no mutex, because bool is atomic
lightThread(lightThreadDispatch& dispatch); lightThread(lightThreadDispatch& dispatch);
~lightThread(); ~lightThread();

@ -1,8 +1,6 @@
//original file from https://github.com/Baughn/Dwarf-Fortress--libgraphics- //original file from https://github.com/Baughn/Dwarf-Fortress--libgraphics-
#pragma once #pragma once
#include "tinythread.h"
#include "Core.h" #include "Core.h"
#include <VTableInterpose.h> #include <VTableInterpose.h>
#include "df/renderer.h" #include "df/renderer.h"