Skip to content

Commit

Permalink
move mingw-std-threads from mingwlibs to engine folder
Browse files Browse the repository at this point in the history
(it's small and I may need to change it)
  • Loading branch information
ashdnazg committed Oct 18, 2016
1 parent 24c5a8a commit ec55556
Show file tree
Hide file tree
Showing 8 changed files with 753 additions and 3 deletions.
2 changes: 2 additions & 0 deletions CMakeLists.txt
Expand Up @@ -158,6 +158,8 @@ else (UNIX AND NOT MINGW)
set(Boost_USE_STATIC_LIBS ON)
set(GLEW_STATIC ON)
set(EXE_FLAGS WIN32)
else()
INCLUDE_DIRECTORIES(rts/lib/mingw-std-threads)
endif()
endif (UNIX AND NOT MINGW)

Expand Down
25 changes: 25 additions & 0 deletions LICENSE
Expand Up @@ -75,3 +75,28 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

### mingw-std-threads
Copyright (c) 2016, Mega Limited
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6 changes: 3 additions & 3 deletions rts/System/Threading/SpringThreading.h
Expand Up @@ -16,9 +16,9 @@
#include <thread>
#include <condition_variable>
#if defined(__MINGW32__) && !defined(_GLIBCXX_HAS_GTHREADS)
#include <mingw-std-threads/mingw.thread.h>
#include <mingw-std-threads/mingw.condition_variable.h>
#include <mingw-std-threads/mingw.mutex.h>
#include <mingw.thread.h>
#include <mingw.condition_variable.h>
#include <mingw.mutex.h>

////////////////
// BEGIN UGLY HACK
Expand Down
24 changes: 24 additions & 0 deletions rts/lib/mingw-std-threads/LICENSE
@@ -0,0 +1,24 @@
Copyright (c) 2016, Mega Limited
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

46 changes: 46 additions & 0 deletions rts/lib/mingw-std-threads/README.md
@@ -0,0 +1,46 @@
mingw-std-threads
=================

Standard C++11 threading classes implementation, which are currently still missing
on MinGW GCC.

Windows compatibility
=====================
This implementation should work with Windows XP (regardless of service pack), or newer.
Since Vista, Windows has native condition variables, but we do not rely on them, to keep compatibility
with Windows XP.

Usage
=====

This is a header-only library. To use, just include the corresponding mingw.xxx.h file, where
xxx would be the name of the standard header that you would normally include.
For additional mutex helper classes, such as std::scoped_guard or std::unique_lock, you need to
include &lt;mutex&gt; before including mingw.mutex.h

Compatibility
=============

This code has been tested to work with MinGW-w64 5.3.0, but should work with any other MinGW version
that has the std threading classes missing, has C++11 support for lambda functions, variadic
templates, and has working mutex helper classes in &lt;mutex&gt;.

Switching from the win32-pthread based implemetation
====================================================
It seems that recent versions of mingw-w64 include a win32 port of pthreads, and have
the std::thread, std::mutex etc classes implemented and working, based on that compatibility
layer. This is a somewhat heavier implementation, as it brings a not very thin abstraction layer.
So you may still want to use this implementation for efficiency purposes. Unfortunately you can't use it
standalone and independent of the system &lt;mutex&gt; header, as it relies on it for std::unique_lock and other
non-trivial utility classes. In that case you will need to edit the c++-config.h file of your MinGW setup
and comment out the definition of _GLIBCXX_HAS_GTHREADS. This will cause the system headers to not define the
actual thread, mutex, etc classes, but still define the necessary utility classes.

Why MinGW has no threading classes
==================================
It seems that for cross-platform threading implementation, the GCC standard library relies on
the gthreads/pthreads library. If this library is not available, as is the case with MinGW, the
std::thread, std::mutex, std::condition_variable are not defined. However, higher-level mutex
helper classes are still defined in &lt;mutex&gt; and are usable. Hence, this implementation
does not re-define them, and to use these helpers, you should include &lt;mutex&gt; as well, as explained
in the usage section.
211 changes: 211 additions & 0 deletions rts/lib/mingw-std-threads/mingw.condition_variable.h
@@ -0,0 +1,211 @@
/**
* @file condition_variable.h
* @brief std::condition_variable implementation for MinGW
*
* (c) 2013-2016 by Mega Limited, Auckland, New Zealand
* @author Alexander Vassilev
*
* @copyright Simplified (2-clause) BSD License.
* You should have received a copy of the license along with this
* program.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* @note
* This file may become part of the mingw-w64 runtime package. If/when this happens,
* the appropriate license will be added, i.e. this code will become dual-licensed,
* and the current BSD 2-clause license will stay.
*/

#ifndef MINGW_CONDITIONAL_VARIABLE_H
#define MINGW_CONDITIONAL_VARIABLE_H
#include <atomic>
#include <assert.h>
#include "mingw.mutex.h"
#include <chrono>
#include <system_error>
#include <windows.h>
#ifdef _GLIBCXX_HAS_GTHREADS
#error This version of MinGW seems to include a win32 port of pthreads, and probably \
already has C++11 std threading classes implemented, based on pthreads. \
It is likely that you will get errors about redefined classes, and unfortunately \
this implementation can not be used standalone and independent of the system <mutex>\
header, since it relies on it for \
std::unique_lock and other utility classes. If you would still like to use this \
implementation (as it is more lightweight), you have to edit the \
c++-config.h system header of your MinGW to not define _GLIBCXX_HAS_GTHREADS. \
This will prevent system headers from defining actual threading classes while still \
defining the necessary utility classes.
#endif

namespace std
{

enum class cv_status { no_timeout, timeout };
class condition_variable_any
{
protected:
recursive_mutex mMutex;
atomic<int> mNumWaiters;
HANDLE mSemaphore;
HANDLE mWakeEvent;
public:
typedef HANDLE native_handle_type;
native_handle_type native_handle() {return mSemaphore;}
condition_variable_any(const condition_variable_any&) = delete;
condition_variable_any& operator=(const condition_variable_any&) = delete;
condition_variable_any()
:mNumWaiters(0), mSemaphore(CreateSemaphore(NULL, 0, 0xFFFF, NULL)),
mWakeEvent(CreateEvent(NULL, FALSE, FALSE, NULL))
{}
~condition_variable_any() { CloseHandle(mWakeEvent); CloseHandle(mSemaphore); }
protected:
template <class M>
bool wait_impl(M& lock, DWORD timeout)
{
{
lock_guard<recursive_mutex> guard(mMutex);
mNumWaiters++;
}
lock.unlock();
DWORD ret = WaitForSingleObject(mSemaphore, timeout);

mNumWaiters--;
SetEvent(mWakeEvent);
lock.lock();
if (ret == WAIT_OBJECT_0)
return true;
else if (ret == WAIT_TIMEOUT)
return false;
//2 possible cases:
//1)The point in notify_all() where we determine the count to
//increment the semaphore with has not been reached yet:
//we just need to decrement mNumWaiters, but setting the event does not hurt
//
//2)Semaphore has just been released with mNumWaiters just before
//we decremented it. This means that the semaphore count
//after all waiters finish won't be 0 - because not all waiters
//woke up by acquiring the semaphore - we woke up by a timeout.
//The notify_all() must handle this grafecully
//
else
throw system_error(EPROTO, generic_category());
}
public:
template <class M>
void wait(M& lock)
{
wait_impl(lock, INFINITE);
}
template <class M, class Predicate>
void wait(M& lock, Predicate pred)
{
while(!pred())
{
wait(lock);
};
}

void notify_all() noexcept
{
lock_guard<recursive_mutex> lock(mMutex); //block any further wait requests until all current waiters are unblocked
if (mNumWaiters.load() <= 0)
return;

ReleaseSemaphore(mSemaphore, mNumWaiters, NULL);
while(mNumWaiters > 0)
{
auto ret = WaitForSingleObject(mWakeEvent, 1000);
if ((ret == WAIT_FAILED) || (ret == WAIT_ABANDONED))
throw system_error(EPROTO, generic_category());
}
assert(mNumWaiters == 0);
//in case some of the waiters timed out just after we released the
//semaphore by mNumWaiters, it won't be zero now, because not all waiters
//woke up by acquiring the semaphore. So we must zero the semaphore before
//we accept waiters for the next event
//See _wait_impl for details
while(WaitForSingleObject(mSemaphore, 0) == WAIT_OBJECT_0);
}
void notify_one() noexcept
{
lock_guard<recursive_mutex> lock(mMutex);
if (!mNumWaiters)
return;
int targetWaiters = mNumWaiters.load() - 1;
ReleaseSemaphore(mSemaphore, 1, NULL);
while(mNumWaiters > targetWaiters)
{
auto ret = WaitForSingleObject(mWakeEvent, 1000);
if ((ret == WAIT_FAILED) || (ret == WAIT_ABANDONED))
throw system_error(EPROTO, generic_category());
}
assert(mNumWaiters == targetWaiters);
}
template <class M, class Rep, class Period>
std::cv_status wait_for(M& lock,
const std::chrono::duration<Rep, Period>& rel_time)
{
long long timeout = chrono::duration_cast<chrono::milliseconds>(rel_time).count();
if (timeout < 0)
timeout = 0;
bool ret = wait_impl(lock, (DWORD)timeout);
return ret?cv_status::no_timeout:cv_status::timeout;
}

template <class M, class Rep, class Period, class Predicate>
bool wait_for(M& lock,
const std::chrono::duration<Rep, Period>& rel_time, Predicate pred)
{
wait_for(lock, rel_time);
return pred();
}
template <class M, class Clock, class Duration>
cv_status wait_until (M& lock,
const chrono::time_point<Clock,Duration>& abs_time)
{
return wait_for(lock, abs_time - Clock::now());
}
template <class M, class Clock, class Duration, class Predicate>
bool wait_until (M& lock,
const std::chrono::time_point<Clock, Duration>& abs_time,
Predicate pred)
{
auto time = abs_time - Clock::now();
if (time < 0)
return pred();
else
return wait_for(lock, time, pred);
}
};
class condition_variable: protected condition_variable_any
{
protected:
typedef condition_variable_any base;
public:
using base::native_handle_type;
using base::native_handle;
using base::base;
using base::notify_all;
using base::notify_one;
void wait(unique_lock<mutex> &lock)
{ base::wait(lock); }
template <class Predicate>
void wait(unique_lock<mutex>& lock, Predicate pred)
{ base::wait(lock, pred); }
template <class Rep, class Period>
std::cv_status wait_for(unique_lock<mutex>& lock, const std::chrono::duration<Rep, Period>& rel_time)
{ return base::wait_for(lock, rel_time); }
template <class Rep, class Period, class Predicate>
bool wait_for(unique_lock<mutex>& lock, const std::chrono::duration<Rep, Period>& rel_time, Predicate pred)
{ return base::wait_for(lock, rel_time, pred); }
template <class Clock, class Duration>
cv_status wait_until (unique_lock<mutex>& lock, const chrono::time_point<Clock,Duration>& abs_time)
{ return base::wait_for(lock, abs_time); }
template <class Clock, class Duration, class Predicate>
bool wait_until (unique_lock<mutex>& lock, const std::chrono::time_point<Clock, Duration>& abs_time, Predicate pred)
{ return base::wait_until(lock, abs_time, pred); }
};
}
#endif // MINGW_CONDITIONAL_VARIABLE_H

0 comments on commit ec55556

Please sign in to comment.