aboutsummaryrefslogtreecommitdiff
path: root/libbutl/mingw-thread.hxx
blob: b308dde2005d670bf888b95225fd234ac0e5a42e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/**
* std::thread implementation for MinGW-w64
*
* Copyright (c) 2013-2016 by Mega Limited, Auckland, New Zealand
* Copyright (c) 2022 the build2 authors
*
* Licensed under the 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.
*/

#ifndef LIBBUTL_MINGW_THREAD_HXX
#define LIBBUTL_MINGW_THREAD_HXX

#if !defined(__cplusplus) || (__cplusplus < 201402L)
#  error C++14 compiler required
#endif

#if !defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0601
#  error _WIN32_WINNT should be 0x0601 (Windows 7) or greater
#endif

#include <cstddef>      //  For std::size_t
#include <cerrno>       //  Detect error type.
#include <exception>    //  For std::terminate
#include <system_error> //  For std::system_error
#include <functional>   //  For std::hash, std::invoke (C++17)
#include <tuple>        //  For std::tuple
#include <chrono>       //  For sleep timing.
#include <memory>       //  For std::unique_ptr
#include <iosfwd>       //  Stream output for thread ids.
#include <utility>      //  For std::swap, std::forward

#include <synchapi.h>   //  For WaitForSingleObject
#include <handleapi.h>  //  For CloseHandle, etc.
#include <sysinfoapi.h> //  For GetNativeSystemInfo
#include <processthreadsapi.h>  //  For GetCurrentThreadId

#include <process.h>  //  For _beginthreadex

#if __cplusplus < 201703L
#  include <libbutl/mingw-invoke.hxx>
#endif

namespace mingw_stdthread
{
  // @@ I think can get rid of this in C++14.
  //
  namespace detail
  {
    template<std::size_t...>
    struct IntSeq {};

    template<std::size_t N, std::size_t... S>
    struct GenIntSeq : GenIntSeq<N-1, N-1, S...> { };

    template<std::size_t... S>
    struct GenIntSeq<0, S...> { typedef IntSeq<S...> type; };

//    Use a template specialization to avoid relying on compiler optimization
//  when determining the parameter integer sequence.
    template<class Func, class T, typename... Args>
    class ThreadFuncCall;
// We can't define the Call struct in the function - the standard forbids template methods in that case
    template<class Func, std::size_t... S, typename... Args>
    class ThreadFuncCall<Func, detail::IntSeq<S...>, Args...>
    {
        static_assert(sizeof...(S) == sizeof...(Args), "Args must match.");
        using Tuple = std::tuple<typename std::decay<Args>::type...>;
        typename std::decay<Func>::type mFunc;
        Tuple mArgs;

    public:
        ThreadFuncCall(Func&& aFunc, Args&&... aArgs)
          : mFunc(std::forward<Func>(aFunc)),
            mArgs(std::forward<Args>(aArgs)...)
        {
        }

        void callFunc()
        {
#if __cplusplus < 201703L
          detail::invoke(std::move(mFunc), std::move(std::get<S>(mArgs)) ...);
#else
          std::invoke (std::move(mFunc), std::move(std::get<S>(mArgs)) ...);
#endif
        }
    };

    // Allow construction of threads without exposing implementation.
    class ThreadIdTool;
  }

  class thread
  {
  public:
    class id
    {
      DWORD mId = 0;
      friend class thread;
      friend class std::hash<id>;
      friend class detail::ThreadIdTool;
      explicit id(DWORD aId) noexcept : mId(aId){}
    public:
      id () noexcept = default;
      friend bool operator==(id x, id y) noexcept {return x.mId == y.mId; }
      friend bool operator!=(id x, id y) noexcept {return x.mId != y.mId; }
      friend bool operator< (id x, id y) noexcept {return x.mId <  y.mId; }
      friend bool operator<=(id x, id y) noexcept {return x.mId <= y.mId; }
      friend bool operator> (id x, id y) noexcept {return x.mId >  y.mId; }
      friend bool operator>=(id x, id y) noexcept {return x.mId >= y.mId; }

      template<class _CharT, class _Traits>
      friend std::basic_ostream<_CharT, _Traits>&
      operator<<(std::basic_ostream<_CharT, _Traits>& __out, id __id)
      {
        if (__id.mId == 0)
        {
          return __out << "<invalid std::thread::id>";
        }
        else
        {
          return __out << __id.mId;
        }
      }
    };
  private:
    static constexpr HANDLE kInvalidHandle = nullptr;
    static constexpr DWORD kInfinite = 0xffffffffl;
    HANDLE mHandle;
    id mThreadId;

    template <class Call>
    static unsigned __stdcall threadfunc(void* arg)
    {
      std::unique_ptr<Call> call(static_cast<Call*>(arg));
      call->callFunc();
      return 0;
    }

    static unsigned int _hardware_concurrency_helper() noexcept
    {
      SYSTEM_INFO sysinfo;
      ::GetNativeSystemInfo(&sysinfo);
      return sysinfo.dwNumberOfProcessors;
    }
  public:
    typedef HANDLE native_handle_type;
    id get_id() const noexcept {return mThreadId;}
    native_handle_type native_handle() const {return mHandle;}
    thread(): mHandle(kInvalidHandle), mThreadId(){}

    thread(thread&& other)
        :mHandle(other.mHandle), mThreadId(other.mThreadId)
    {
      other.mHandle = kInvalidHandle;
      other.mThreadId = id{};
    }

    thread(const thread &other) = delete;

    template<class Func, typename... Args>
    explicit thread(Func&& func, Args&&... args) : mHandle(), mThreadId()
    {
      // Instead of INVALID_HANDLE_VALUE, _beginthreadex returns 0.

      using ArgSequence = typename detail::GenIntSeq<sizeof...(Args)>::type;
      using Call = detail::ThreadFuncCall<Func, ArgSequence, Args...>;
      auto call = new Call(std::forward<Func>(func), std::forward<Args>(args)...);
      unsigned int id_receiver;
      auto int_handle = _beginthreadex(NULL, 0, threadfunc<Call>,
                                       static_cast<LPVOID>(call), 0, &id_receiver);
      if (int_handle == 0)
      {
        mHandle = kInvalidHandle;
        int errnum = errno;
        delete call;
         //  Note: Should only throw EINVAL, EAGAIN, EACCES
        throw std::system_error(errnum, std::generic_category());
      } else {
        mThreadId.mId = id_receiver;
        mHandle = reinterpret_cast<HANDLE>(int_handle);
      }
    }

    bool joinable() const {return mHandle != kInvalidHandle;}

    //  Note: Due to lack of synchronization, this function has a race
    //  condition if called concurrently, which leads to undefined
    //  behavior. The same applies to all other member functions of this
    //  class, but this one is mentioned explicitly.
    void join()
    {
        using namespace std;
        if (get_id() == id(GetCurrentThreadId()))
            throw system_error(make_error_code(errc::resource_deadlock_would_occur));
        if (mHandle == kInvalidHandle)
            throw system_error(make_error_code(errc::no_such_process));
        if (!joinable())
            throw system_error(make_error_code(errc::invalid_argument));
        WaitForSingleObject(mHandle, kInfinite);
        CloseHandle(mHandle);
        mHandle = kInvalidHandle;
        mThreadId = id{};
    }

    ~thread()
    {
      if (joinable())
      {
        // @@ TODO
        /*
#ifndef NDEBUG
        std::printf("Error: Must join() or detach() a thread before \
destroying it.\n");
#endif
        */
        std::terminate();
      }
    }
    thread& operator=(const thread&) = delete;
    thread& operator=(thread&& other) noexcept
    {
      if (joinable())
      {
        // @@ TODO
        /*
#ifndef NDEBUG
        std::printf("Error: Must join() or detach() a thread before \
moving another thread to it.\n");
#endif
        */
        std::terminate();
      }
      swap(other);
      return *this;
    }
    void swap(thread& other) noexcept
    {
      std::swap(mHandle, other.mHandle);
      std::swap(mThreadId.mId, other.mThreadId.mId);
    }

    static unsigned int hardware_concurrency() noexcept
    {
      // @@ TODO: this seems like a bad idea.
      //
      /*static*/ unsigned int cached = _hardware_concurrency_helper();
      return cached;
    }

    void detach()
    {
      if (!joinable())
      {
        using namespace std;
        throw system_error(make_error_code(errc::invalid_argument));
      }
      if (mHandle != kInvalidHandle)
      {
        CloseHandle(mHandle);
        mHandle = kInvalidHandle;
      }
      mThreadId = id{};
    }
  };

  namespace detail
  {
    class ThreadIdTool
    {
    public:
      static thread::id make_id (DWORD base_id) noexcept
      {
        return thread::id(base_id);
      }
    };
  }

  namespace this_thread
  {
    inline thread::id get_id() noexcept
    {
      return detail::ThreadIdTool::make_id(GetCurrentThreadId());
    }
    inline void yield() noexcept {Sleep(0);}
    template< class Rep, class Period >
    void sleep_for( const std::chrono::duration<Rep,Period>& sleep_duration)
    {
      static constexpr DWORD kInfinite = 0xffffffffl;
      using namespace std::chrono;
      using rep = milliseconds::rep;
      rep ms = duration_cast<milliseconds>(sleep_duration).count();
      while (ms > 0)
      {
        constexpr rep kMaxRep = static_cast<rep>(kInfinite - 1);
        auto sleepTime = (ms < kMaxRep) ? ms : kMaxRep;
        Sleep(static_cast<DWORD>(sleepTime));
        ms -= sleepTime;
      }
    }
    template <class Clock, class Duration>
    void sleep_until(const std::chrono::time_point<Clock,Duration>& sleep_time)
    {
      sleep_for(sleep_time-Clock::now());
    }
  }
}

namespace std
{
  // Specialize hash for this implementation's thread::id, even if the
  // std::thread::id already has a hash.
  template<>
  struct hash<mingw_stdthread::thread::id>
  {
    typedef mingw_stdthread::thread::id argument_type;
    typedef size_t result_type;
    size_t operator() (const argument_type & i) const noexcept
    {
      return i.mId;
    }
  };
}

#endif // LIBBUTL_MINGW_THREAD_HXX