From 54769ebdbff7586e6ba29c7bfab8327282840417 Mon Sep 17 00:00:00 2001 From: Paxton Schweigert Date: Tue, 20 Dec 2022 17:56:58 -0800 Subject: [PATCH] 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 --- .ycm_extra_conf.py | 1 - CMakeLists.txt | 1 - LICENSE.rst | 2 - depends/CMakeLists.txt | 1 - depends/tthread/CMakeLists.txt | 6 - depends/tthread/tinythread.cpp | 313 ----------- depends/tthread/tinythread.h | 714 -------------------------- library/CMakeLists.txt | 6 +- library/ColorText.cpp | 3 - library/Console-posix.cpp | 27 +- library/Console-windows.cpp | 25 +- library/DataDefs.cpp | 7 +- library/LuaApi.cpp | 4 +- library/LuaTools.cpp | 1 - library/LuaTypes.cpp | 1 - library/LuaWrapper.cpp | 1 - library/PlugLoad-windows.cpp | 2 - library/PluginManager.cpp | 49 +- library/RemoteClient.cpp | 2 - library/include/Console.h | 11 +- library/include/PluginManager.h | 10 +- plugins/CMakeLists.txt | 2 +- plugins/devel/memview.cpp | 6 +- plugins/rendermax/CMakeLists.txt | 2 +- plugins/rendermax/renderer_light.cpp | 29 +- plugins/rendermax/renderer_light.hpp | 14 +- plugins/rendermax/renderer_opengl.hpp | 2 - 27 files changed, 82 insertions(+), 1160 deletions(-) delete mode 100644 depends/tthread/CMakeLists.txt delete mode 100644 depends/tthread/tinythread.cpp delete mode 100644 depends/tthread/tinythread.h diff --git a/.ycm_extra_conf.py b/.ycm_extra_conf.py index e98f7a2a6..31a336b2b 100644 --- a/.ycm_extra_conf.py +++ b/.ycm_extra_conf.py @@ -19,7 +19,6 @@ default_flags = [ '-I','depends/md5', '-I','depends/jsoncpp/include', '-I','depends/tinyxml', - '-I','depends/tthread', '-I','depends/clsocket/src', '-x','c++', '-D','PROTOBUF_USE_DLLS', diff --git a/CMakeLists.txt b/CMakeLists.txt index 5587c27fc..3b4fe01d9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -384,7 +384,6 @@ else() endif() include_directories(depends/lodepng) -include_directories(depends/tthread) include_directories(depends/clsocket/src) include_directories(depends/xlsxio/include) diff --git a/LICENSE.rst b/LICENSE.rst index 529814423..9c68a71c5 100644 --- a/LICENSE.rst +++ b/LICENSE.rst @@ -31,7 +31,6 @@ luacov_ MIT \(c\) 2007 - 2018 Hisham Muhammad luafilesystem_ MIT \(c\) 2003-2014, Kepler Project lua-profiler_ MIT \(c\) 2002,2003,2004 Pepperfish protobuf_ BSD 3-clause \(c\) 2008, Google Inc. -tinythread_ Zlib \(c\) 2010, Marcus Geelnard tinyxml_ Zlib \(c\) 2000-2006, Lee Thomason UTF-8-decoder_ MIT \(c\) 2008-2010, Bjoern Hoehrmann 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 .. _lua-profiler: http://lua-users.org/wiki/PepperfishProfiler .. _protobuf: https://github.com/google/protobuf -.. _tinythread: http://tinythreadpp.bitsnbites.eu/ .. _tinyxml: http://www.sourceforge.net/projects/tinyxml .. _UTF-8-decoder: http://bjoern.hoehrmann.de/utf-8/decoder/dfa .. _xlsxio: https://github.com/brechtsanders/xlsxio diff --git a/depends/CMakeLists.txt b/depends/CMakeLists.txt index d3cfbb415..536eba63a 100644 --- a/depends/CMakeLists.txt +++ b/depends/CMakeLists.txt @@ -25,7 +25,6 @@ if(NOT TinyXML_FOUND) add_subdirectory(tinyxml) endif() -add_subdirectory(tthread) 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_BUILD_SHARED_LIBS "Build jsoncpp_lib as a shared library." OFF) diff --git a/depends/tthread/CMakeLists.txt b/depends/tthread/CMakeLists.txt deleted file mode 100644 index dfb1d9901..000000000 --- a/depends/tthread/CMakeLists.txt +++ /dev/null @@ -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") diff --git a/depends/tthread/tinythread.cpp b/depends/tthread/tinythread.cpp deleted file mode 100644 index 176bc2ac8..000000000 --- a/depends/tthread/tinythread.cpp +++ /dev/null @@ -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 -#include "tinythread.h" - -#if defined(_TTHREAD_POSIX_) - #include - #include -#elif defined(_TTHREAD_WIN32_) - #include -#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 idMap; - static unsigned long int idCount(1); - - lock_guard 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 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 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 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 -} - -} diff --git a/depends/tthread/tinythread.h b/depends/tthread/tinythread.h deleted file mode 100644 index b5ff2f077..000000000 --- a/depends/tthread/tinythread.h +++ /dev/null @@ -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 - #ifdef __UNDEF_LEAN_AND_MEAN - #undef WIN32_LEAN_AND_MEAN - #undef __UNDEF_LEAN_AND_MEAN - #endif -#else - #include - #include - #include - #include -#endif - -// Generic includes -#include - -/// 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 guard(m); -/// ++ counter; -/// } -/// @endcode - -template -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 guard(m); -/// while(count < targetCount) -/// cond.wait(m); -/// } -/// -/// // Increment the counter, and notify waiting threads -/// void increment() -/// { -/// lock_guard 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 - 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: - /// void fun(void * arg) - /// @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 - 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 duration { - private: - _Rep rep_; - public: - typedef _Rep rep; - typedef _Period period; - - /// Construct a duration object with the given duration. - template - 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 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_ diff --git a/library/CMakeLists.txt b/library/CMakeLists.txt index e9ec8f717..a668a0773 100644 --- a/library/CMakeLists.txt +++ b/library/CMakeLists.txt @@ -319,12 +319,12 @@ if(UNIX) endif() if(APPLE) - set(PROJECT_LIBS dl dfhack-md5 ${DFHACK_TINYXML} dfhack-tinythread) + set(PROJECT_LIBS dl dfhack-md5 ${DFHACK_TINYXML}) elseif(UNIX) - set(PROJECT_LIBS rt dl dfhack-md5 ${DFHACK_TINYXML} dfhack-tinythread) + set(PROJECT_LIBS rt dl dfhack-md5 ${DFHACK_TINYXML}) else(WIN32) # 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() set(VERSION_SRCS DFHackVersion.cpp) diff --git a/library/ColorText.cpp b/library/ColorText.cpp index d528cb4c7..8dc5cc5dc 100644 --- a/library/ColorText.cpp +++ b/library/ColorText.cpp @@ -55,9 +55,6 @@ POSSIBILITY OF SUCH DAMAGE. using namespace std; using namespace DFHack; -#include "tinythread.h" -using namespace tthread; - bool color_ostream::log_errors_to_stderr = false; void color_ostream::flush_buffer(bool flush) diff --git a/library/Console-posix.cpp b/library/Console-posix.cpp index 49f54c5ef..3b91f3a23 100644 --- a/library/Console-posix.cpp +++ b/library/Console-posix.cpp @@ -79,9 +79,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "Hooks.h" using namespace DFHack; -#include "tinythread.h" -using namespace tthread; - static int isUnsupportedTerm(void) { static const char *unsupported_term[] = {"dumb","cons25",NULL}; @@ -403,7 +400,7 @@ namespace DFHack prompt_refresh(); } /// 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) return Console::FAILURE; @@ -518,7 +515,7 @@ namespace DFHack 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; size_t plen = prompt.size(); @@ -841,7 +838,7 @@ Console::Console() d = 0; inited = false; // 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() { @@ -890,7 +887,7 @@ bool Console::shutdown(void) if(!d) return true; d->reset_color(); - lock_guard g(*wlock); + std::lock_guard lock{*wlock}; close(d->exit_pipe[1]); if (d->state != Private::con_lineedit) inited = false; @@ -917,14 +914,14 @@ void Console::end_batch() void Console::flush_proxy() { - lock_guard g(*wlock); + std::lock_guard lock{*wlock}; if (inited) d->flush(); } void Console::add_text(color_value color, const std::string &text) { - lock_guard g(*wlock); + std::lock_guard lock{*wlock}; if (inited) d->print_text(color, text); else @@ -933,7 +930,7 @@ void Console::add_text(color_value color, const std::string &text) int Console::get_columns(void) { - lock_guard g(*wlock); + std::lock_guard lock{*wlock}; int ret = Console::FAILURE; if(inited) ret = d->get_columns(); @@ -942,7 +939,7 @@ int Console::get_columns(void) int Console::get_rows(void) { - lock_guard g(*wlock); + std::lock_guard lock{*wlock}; int ret = Console::FAILURE; if(inited) ret = d->get_rows(); @@ -951,28 +948,28 @@ int Console::get_rows(void) void Console::clear() { - lock_guard g(*wlock); + std::lock_guard lock{*wlock}; if(inited) d->clear(); } void Console::gotoxy(int x, int y) { - lock_guard g(*wlock); + std::lock_guard lock{*wlock}; if(inited) d->gotoxy(x,y); } void Console::cursor(bool enable) { - lock_guard g(*wlock); + std::lock_guard lock{*wlock}; if(inited) d->cursor(enable); } int Console::lineedit(const std::string & prompt, std::string & output, CommandHistory & ch) { - lock_guard g(*wlock); + std::lock_guard lock{*wlock}; int ret = Console::SHUTDOWN; if(inited) { ret = d->lineedit(prompt,output,wlock,ch); diff --git a/library/Console-windows.cpp b/library/Console-windows.cpp index 20d943b18..85934b2f3 100644 --- a/library/Console-windows.cpp +++ b/library/Console-windows.cpp @@ -58,9 +58,6 @@ POSSIBILITY OF SUCH DAMAGE. #include using namespace DFHack; -#include "tinythread.h" -using namespace tthread; - // FIXME: maybe make configurable with an ini option? #define MAX_CONSOLE_LINES 999 @@ -262,7 +259,7 @@ namespace DFHack 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! 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) return Console::FAILURE; @@ -472,7 +469,7 @@ bool Console::init(bool) // Allocate a console! AllocConsole(); d->ConsoleWindow = GetConsoleWindow(); - wlock = new recursive_mutex(); + wlock = new std::recursive_mutex(); HMENU hm = GetSystemMenu(d->ConsoleWindow,false); DeleteMenu(hm, SC_CLOSE, MF_BYCOMMAND); @@ -514,7 +511,7 @@ bool Console::init(bool) // FIXME: looks awfully empty, doesn't it? bool Console::shutdown(void) { - lock_guard g(*wlock); + std::lock_guard lock{*wlock}; FreeConsole(); inited = false; return true; @@ -540,21 +537,21 @@ void Console::end_batch() void Console::flush_proxy() { - lock_guard g(*wlock); + std::lock_guard lock{*wlock}; if (inited) d->flush(); } void Console::add_text(color_value color, const std::string &text) { - lock_guard g(*wlock); + std::lock_guard lock{*wlock}; if (inited) d->print_text(color, text); } int Console::get_columns(void) { - lock_guard g(*wlock); + std::lock_guard lock{*wlock}; int ret = -1; if(inited) ret = d->get_columns(); @@ -563,7 +560,7 @@ int Console::get_columns(void) int Console::get_rows(void) { - lock_guard g(*wlock); + std::lock_guard lock{*wlock}; int ret = -1; if(inited) ret = d->get_rows(); @@ -572,21 +569,21 @@ int Console::get_rows(void) void Console::clear() { - lock_guard g(*wlock); + std::lock_guard lock{*wlock}; if(inited) d->clear(); } void Console::gotoxy(int x, int y) { - lock_guard g(*wlock); + std::lock_guard lock{*wlock}; if(inited) d->gotoxy(x,y); } void Console::cursor(bool enable) { - lock_guard g(*wlock); + std::lock_guard lock{*wlock}; if(inited) d->cursor(enable); } diff --git a/library/DataDefs.cpp b/library/DataDefs.cpp index cd261d50f..1c66a4ebe 100644 --- a/library/DataDefs.cpp +++ b/library/DataDefs.cpp @@ -31,7 +31,6 @@ distribution. #include "MemAccess.h" #include "Core.h" #include "VersionInfo.h" -#include "tinythread.h" // must be last due to MS stupidity #include "DataDefs.h" #include "DataIdentity.h" @@ -118,12 +117,12 @@ std::string compound_identity::getFullName() return getName(); } -static tthread::mutex *known_mutex = NULL; +static std::mutex *known_mutex = NULL; void compound_identity::Init(Core *core) { if (!known_mutex) - known_mutex = new tthread::mutex(); + known_mutex = new std::mutex(); // This cannot be done in the constructors, because // 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, // since the table is only written once per class. - tthread::lock_guard lock(*known_mutex); + std::lock_guard lock(*known_mutex); std::map::iterator it = known.find(vtable); diff --git a/library/LuaApi.cpp b/library/LuaApi.cpp index 5836561f8..1769baa90 100644 --- a/library/LuaApi.cpp +++ b/library/LuaApi.cpp @@ -33,14 +33,12 @@ distribution. #include "Core.h" #include "Error.h" #include "VersionInfo.h" -#include "tinythread.h" // must be last due to MS stupidity #include "DataDefs.h" #include "DataIdentity.h" #include "DataFuncs.h" #include "DFHackVersion.h" #include "PluginManager.h" -#include "tinythread.h" #include "md5wrapper.h" #include "modules/Buildings.h" @@ -3703,7 +3701,7 @@ static int internal_getCommandDescription(lua_State *L) static int internal_threadid(lua_State *L) { std::stringstream ss; - ss << tthread::this_thread::get_id(); + ss << std::this_thread::get_id(); int i; ss >> i; lua_pushinteger(L, i); diff --git a/library/LuaTools.cpp b/library/LuaTools.cpp index 87699641d..a73c41f37 100644 --- a/library/LuaTools.cpp +++ b/library/LuaTools.cpp @@ -32,7 +32,6 @@ distribution. #include "MemAccess.h" #include "Core.h" #include "VersionInfo.h" -#include "tinythread.h" // must be last due to MS stupidity #include "DataDefs.h" #include "DataIdentity.h" diff --git a/library/LuaTypes.cpp b/library/LuaTypes.cpp index cbf1779be..30565ea64 100644 --- a/library/LuaTypes.cpp +++ b/library/LuaTypes.cpp @@ -32,7 +32,6 @@ distribution. #include "Core.h" #include "Error.h" #include "VersionInfo.h" -#include "tinythread.h" // must be last due to MS stupidity #include "DataDefs.h" #include "DataIdentity.h" diff --git a/library/LuaWrapper.cpp b/library/LuaWrapper.cpp index 9d2357c70..3e82778b2 100644 --- a/library/LuaWrapper.cpp +++ b/library/LuaWrapper.cpp @@ -32,7 +32,6 @@ distribution. #include "MemAccess.h" #include "Core.h" #include "VersionInfo.h" -#include "tinythread.h" // must be last due to MS stupidity #include "DataDefs.h" #include "DataIdentity.h" diff --git a/library/PlugLoad-windows.cpp b/library/PlugLoad-windows.cpp index d6ce8cdbf..a2923e902 100644 --- a/library/PlugLoad-windows.cpp +++ b/library/PlugLoad-windows.cpp @@ -34,8 +34,6 @@ distribution. #include "Hooks.h" #include -#include "tinythread.h" - /* * Plugin loading functions */ diff --git a/library/PluginManager.cpp b/library/PluginManager.cpp index 3670755fd..71c1453b2 100644 --- a/library/PluginManager.cpp +++ b/library/PluginManager.cpp @@ -43,22 +43,14 @@ distribution. using namespace DFHack; +#include #include #include #include using namespace std; -#include "tinythread.h" - #include -#define MUTEX_GUARD(lock) auto lock_##__LINE__ = make_mutex_guard(lock); -template -tthread::lock_guard make_mutex_guard (T *mutex) -{ - return tthread::lock_guard(*mutex); -} - #if defined(_LINUX) static const string plugin_suffix = ".plug.so"; #elif defined(_DARWIN) @@ -82,8 +74,8 @@ struct Plugin::RefLock RefLock() { refcount = 0; - wakeup = new tthread::condition_variable(); - mut = new tthread::mutex(); + wakeup = new std::condition_variable(); + mut = new std::mutex(); } ~RefLock() { @@ -113,13 +105,14 @@ struct Plugin::RefLock } void wait() { + std::unique_lock lock{*mut, std::defer_lock}; while(refcount) { - wakeup->wait(*mut); + wakeup->wait(lock); } } - tthread::condition_variable * wakeup; - tthread::mutex * mut; + std::condition_variable * wakeup; + std::mutex * mut; int refcount; }; @@ -822,8 +815,8 @@ void Plugin::push_function(lua_State *state, LuaFunction *fn) PluginManager::PluginManager(Core * core) : core(core) { - plugin_mutex = new tthread::recursive_mutex(); - cmdlist_mutex = new tthread::mutex(); + plugin_mutex = new std::recursive_mutex(); + cmdlist_mutex = new std::mutex(); } PluginManager::~PluginManager() @@ -898,7 +891,7 @@ vector PluginManager::listPlugins() void PluginManager::refresh() { - MUTEX_GUARD(plugin_mutex); + lock_guard lock{*plugin_mutex}; auto files = listPlugins(); for (auto f = files.begin(); f != files.end(); ++f) { @@ -909,7 +902,7 @@ void PluginManager::refresh() bool PluginManager::load (const string &name) { - MUTEX_GUARD(plugin_mutex); + lock_guard lock{*plugin_mutex}; if (!(*this)[name] && !addPlugin(name)) return false; Plugin *p = (*this)[name]; @@ -923,7 +916,7 @@ bool PluginManager::load (const string &name) bool PluginManager::loadAll() { - MUTEX_GUARD(plugin_mutex); + lock_guard lock{*plugin_mutex}; auto files = listPlugins(); bool ok = true; // load all plugins in hack/plugins @@ -937,7 +930,7 @@ bool PluginManager::loadAll() bool PluginManager::unload (const string &name) { - MUTEX_GUARD(plugin_mutex); + lock_guard lock{*plugin_mutex}; if (!(*this)[name]) { Core::printerr("Plugin does not exist: %s\n", name.c_str()); @@ -948,7 +941,7 @@ bool PluginManager::unload (const string &name) bool PluginManager::unloadAll() { - MUTEX_GUARD(plugin_mutex); + lock_guard lock{*plugin_mutex}; bool ok = true; // only try to unload plugins that are in all_plugins 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, // "load(name);" otherwise - MUTEX_GUARD(plugin_mutex); + lock_guard lock{*plugin_mutex}; if (!(*this)[name]) return load(name); if (!unload(name)) @@ -973,7 +966,7 @@ bool PluginManager::reload (const string &name) bool PluginManager::reloadAll() { - MUTEX_GUARD(plugin_mutex); + lock_guard lock{*plugin_mutex}; bool ok = true; if (!unloadAll()) ok = false; @@ -984,7 +977,7 @@ bool PluginManager::reloadAll() Plugin *PluginManager::getPluginByCommand(const std::string &command) { - tthread::lock_guard lock(*cmdlist_mutex); + lock_guard lock{*cmdlist_mutex}; map ::iterator iter = command_map.find(command); if (iter != command_map.end()) return iter->second; @@ -1019,7 +1012,7 @@ void PluginManager::OnStateChange(color_ostream &out, state_change_event event) void PluginManager::registerCommands( Plugin * p ) { - cmdlist_mutex->lock(); + lock_guard lock{*cmdlist_mutex}; vector & cmds = p->commands; for (size_t i = 0; i < cmds.size();i++) { @@ -1032,18 +1025,16 @@ void PluginManager::registerCommands( Plugin * p ) } command_map[name] = p; } - cmdlist_mutex->unlock(); } void PluginManager::unregisterCommands( Plugin * p ) { - cmdlist_mutex->lock(); + lock_guard lock{*cmdlist_mutex}; vector & cmds = p->commands; for(size_t i = 0; i < cmds.size();i++) { command_map.erase(cmds[i].name); } - cmdlist_mutex->unlock(); } void PluginManager::doSaveData(color_ostream &out) @@ -1070,7 +1061,7 @@ void PluginManager::doLoadData(color_ostream &out) Plugin *PluginManager::operator[] (std::string name) { - MUTEX_GUARD(plugin_mutex); + lock_guard lock{*plugin_mutex}; if (all_plugins.find(name) == all_plugins.end()) { if (Filesystem::isfile(getPluginPath(name))) diff --git a/library/RemoteClient.cpp b/library/RemoteClient.cpp index 0aa68eb51..20990428d 100644 --- a/library/RemoteClient.cpp +++ b/library/RemoteClient.cpp @@ -56,10 +56,8 @@ POSSIBILITY OF SUCH DAMAGE. #include #include "json/json.h" -#include "tinythread.h" using namespace DFHack; -using namespace tthread; using dfproto::CoreTextNotification; diff --git a/library/include/Console.h b/library/include/Console.h index 39a19b152..5cfdba3e0 100644 --- a/library/include/Console.h +++ b/library/include/Console.h @@ -31,15 +31,10 @@ distribution. #include #include #include +#include #include #include -namespace tthread -{ - class mutex; - class recursive_mutex; - class condition_variable; - class thread; -} + namespace DFHack { class CommandHistory @@ -176,7 +171,7 @@ namespace DFHack bool show(); private: Private * d; - tthread::recursive_mutex * wlock; + std::recursive_mutex * wlock; std::atomic inited; }; } diff --git a/library/include/PluginManager.h b/library/include/PluginManager.h index 5cf8bb390..c67956a5b 100644 --- a/library/include/PluginManager.h +++ b/library/include/PluginManager.h @@ -29,6 +29,7 @@ distribution. #include "ColorText.h" #include "MiscUtils.h" #include +#include #include #include @@ -37,11 +38,6 @@ distribution. typedef struct lua_State lua_State; -namespace tthread -{ - class mutex; - class condition_variable; -} namespace df { struct viewscreen; @@ -280,8 +276,8 @@ namespace DFHack private: Core *core; bool addPlugin(std::string name); - tthread::recursive_mutex * plugin_mutex; - tthread::mutex * cmdlist_mutex; + std::recursive_mutex * plugin_mutex; + std::mutex * cmdlist_mutex; std::map command_map; std::map all_plugins; std::string plugin_path; diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt index 5918f9205..7fc4733ab 100644 --- a/plugins/CMakeLists.txt +++ b/plugins/CMakeLists.txt @@ -131,7 +131,7 @@ if(BUILD_SUPPORTED) #dfhack_plugin(jobutils jobutils.cpp) dfhack_plugin(lair lair.cpp) 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(manipulator manipulator.cpp) #dfhack_plugin(map-render map-render.cpp LINK_LIBRARIES lua) diff --git a/plugins/devel/memview.cpp b/plugins/devel/memview.cpp index 769fe9086..b843e6386 100644 --- a/plugins/devel/memview.cpp +++ b/plugins/devel/memview.cpp @@ -3,7 +3,7 @@ #include "PluginManager.h" #include "MemAccess.h" #include "MiscUtils.h" -#include //not sure if correct +#include #include #include #include @@ -15,7 +15,7 @@ using std::string; using namespace DFHack; uint64_t timeLast=0; -static tthread::mutex* mymutex=0; +static std::mutex* mymutex=0; DFHACK_PLUGIN_IS_ENABLED(is_enabled); @@ -40,7 +40,7 @@ DFhackCExport command_result plugin_init (color_ostream &out, std::vector #include -#include "tinythread.h" - #include "LuaTools.h" #include "modules/Gui.h" @@ -32,7 +30,6 @@ using df::global::gps; using namespace DFHack; using df::coord2d; -using namespace tthread; const float RootTwo = 1.4142135623730950488016887242097f; @@ -108,9 +105,9 @@ lightingEngineViewscreen::lightingEngineViewscreen(renderer_light* target):light { reinit(); defaultSettings(); - int numTreads=tthread::thread::hardware_concurrency(); - if(numTreads==0)numTreads=1; - threading.start(numTreads); + int numThreads=std::thread::hardware_concurrency(); + if(numThreads==0)numThreads=1; + threading.start(numThreads); } 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...) {//wait for occlusion (and lights) to be ready - tthread::lock_guard guard(dispatch.occlusionMutex); + std::unique_lock guard(dispatch.occlusionMutex); 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 continue; if(dispatch.occlusion.size()!=canvas.size()) //oh no somebody resized stuff @@ -1272,7 +1269,7 @@ void lightThread::run() { //get my rectangle (any will do) - tthread::lock_guard guard(dispatch.unprocessedMutex); + std::lock_guard guard(dispatch.unprocessedMutex); if (dispatch.unprocessed.size()==0) { //wtf?? why?! @@ -1288,7 +1285,7 @@ void lightThread::run() } work(); { - tthread::lock_guard guard(dispatch.writeLock); + std::lock_guard guard(dispatch.writeLock); combine();//write it back dispatch.writeCount++; } @@ -1399,11 +1396,11 @@ void lightThread::doLight( int x,int y ) void lightThreadDispatch::signalDoneOcclusion() { { - tthread::lock_guard guardWrite(writeLock); + std::lock_guard guardWrite(writeLock); writeCount=0; } - tthread::lock_guard guard1(occlusionMutex); - tthread::lock_guard guard2(unprocessedMutex); + std::lock_guard guard1(occlusionMutex); + std::lock_guard guard2(unprocessedMutex); while(!unprocessed.empty()) unprocessed.pop(); viewPort=getMapViewport(); @@ -1465,17 +1462,17 @@ void lightThreadDispatch::start(int count) for(int i=0;i 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)); } } void lightThreadDispatch::waitForWrites() { - tthread::lock_guard guard(writeLock); + std::unique_lock lock(writeLock); 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 } } diff --git a/plugins/rendermax/renderer_light.hpp b/plugins/rendermax/renderer_light.hpp index 89a2092d5..f6a158d7f 100644 --- a/plugins/rendermax/renderer_light.hpp +++ b/plugins/rendermax/renderer_light.hpp @@ -1,8 +1,10 @@ #pragma once +#include #include #include #include +#include #include #include @@ -231,18 +233,18 @@ public: std::vector > threadPool; std::vector& lights; - tthread::mutex occlusionMutex; - tthread::condition_variable occlusionDone; //all threads wait for occlusion to finish + std::mutex occlusionMutex; + std::condition_variable occlusionDone; //all threads wait for occlusion to finish bool occlusionReady; - tthread::mutex unprocessedMutex; + std::mutex unprocessedMutex; std::stack unprocessed; //stack of parts of map where lighting is not finished std::vector& occlusion; int& num_diffusion; - tthread::mutex writeLock; //mutex for lightMap + std::mutex writeLock; //mutex for lightMap std::vector& lightMap; - tthread::condition_variable writesDone; + std::condition_variable writesDone; int writeCount; lightThreadDispatch(lightingEngineViewscreen* p); @@ -263,7 +265,7 @@ class lightThread void work(); //main light calculation function void combine(); //combine existing canvas into global lightmap public: - tthread::thread *myThread; + std::thread *myThread; bool isDone; //no mutex, because bool is atomic lightThread(lightThreadDispatch& dispatch); ~lightThread(); diff --git a/plugins/rendermax/renderer_opengl.hpp b/plugins/rendermax/renderer_opengl.hpp index 33952f7f0..da99e0d6c 100644 --- a/plugins/rendermax/renderer_opengl.hpp +++ b/plugins/rendermax/renderer_opengl.hpp @@ -1,8 +1,6 @@ //original file from https://github.com/Baughn/Dwarf-Fortress--libgraphics- #pragma once -#include "tinythread.h" - #include "Core.h" #include #include "df/renderer.h"