summaryrefslogtreecommitdiff
path: root/src/third_party/boost-1.68.0/libs/thread/src/win32/thread.cpp
blob: 9a087f1ac0f4e58719a6357af7d9f3020d719dc5 (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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// (C) Copyright 2007 Anthony Williams
// (C) Copyright 2007 David Deakins
// (C) Copyright 2011-2018 Vicente J. Botet Escriba

//#define BOOST_THREAD_VERSION 3

#include <boost/winapi/config.hpp>
#include <boost/thread/thread_only.hpp>
#include <boost/thread/once.hpp>
#include <boost/thread/tss.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread/detail/tss_hooks.hpp>
#include <boost/thread/future.hpp>
#include <boost/assert.hpp>
#include <boost/cstdint.hpp>
#if defined BOOST_THREAD_USES_DATETIME
#include <boost/date_time/posix_time/conversion.hpp>
#include <boost/thread/thread_time.hpp>
#endif
#include <boost/thread/csbl/memory/unique_ptr.hpp>
#include <memory>
#include <algorithm>
#ifndef UNDER_CE
#include <process.h>
#endif
#include <stdio.h>
#include <windows.h>
#include <boost/predef/platform.h>

#if BOOST_PLAT_WINDOWS_RUNTIME
#include <mutex>
#include <atomic>
#include <Activation.h>
#include <wrl\client.h>
#include <wrl\event.h>
#include <wrl\wrappers\corewrappers.h>
#include <wrl\ftm.h>
#include <windows.system.threading.h>
#pragma comment(lib, "runtimeobject.lib")
#endif

namespace boost
{
  namespace detail
  {
    thread_data_base::~thread_data_base()
    {
        for (notify_list_t::iterator i = notify.begin(), e = notify.end();
                i != e; ++i)
        {
            i->second->unlock();
            i->first->notify_all();
        }
//#ifndef BOOST_NO_EXCEPTIONS
        for (async_states_t::iterator i = async_states_.begin(), e = async_states_.end();
                i != e; ++i)
        {
            (*i)->notify_deferred();
        }
//#endif
    }
  }

    namespace
    {
#ifdef BOOST_THREAD_PROVIDES_ONCE_CXX11
        boost::once_flag current_thread_tls_init_flag;
#else
        boost::once_flag current_thread_tls_init_flag=BOOST_ONCE_INIT;
#endif
#if defined(UNDER_CE)
        // Windows CE does not define the TLS_OUT_OF_INDEXES constant.
#define TLS_OUT_OF_INDEXES 0xFFFFFFFF
#endif
#if !BOOST_PLAT_WINDOWS_RUNTIME
        DWORD current_thread_tls_key=TLS_OUT_OF_INDEXES;
#else
        __declspec(thread) boost::detail::thread_data_base* current_thread_data_base;
#endif

        void create_current_thread_tls_key()
        {
            tss_cleanup_implemented(); // if anyone uses TSS, we need the cleanup linked in
#if !BOOST_PLAT_WINDOWS_RUNTIME
            current_thread_tls_key=TlsAlloc();
            BOOST_ASSERT(current_thread_tls_key!=TLS_OUT_OF_INDEXES);
#endif
        }

        void cleanup_tls_key()
        {
#if !BOOST_PLAT_WINDOWS_RUNTIME
            if(current_thread_tls_key!=TLS_OUT_OF_INDEXES)
            {
                TlsFree(current_thread_tls_key);
                current_thread_tls_key=TLS_OUT_OF_INDEXES;
            }
#endif
        }

        void set_current_thread_data(detail::thread_data_base* new_data)
        {
            boost::call_once(current_thread_tls_init_flag,create_current_thread_tls_key);
#if BOOST_PLAT_WINDOWS_RUNTIME
            current_thread_data_base = new_data;
#else
            if (current_thread_tls_key != TLS_OUT_OF_INDEXES)
            {
                BOOST_VERIFY(TlsSetValue(current_thread_tls_key, new_data));
            }
            else
            {
                BOOST_VERIFY(false);
                //boost::throw_exception(thread_resource_error());
            }
#endif
        }
    }

    namespace detail
    {
      thread_data_base* get_current_thread_data()
      {
#if BOOST_PLAT_WINDOWS_RUNTIME
          return current_thread_data_base;
#else
          if (current_thread_tls_key == TLS_OUT_OF_INDEXES)
          {
              return 0;
          }
          return (detail::thread_data_base*)TlsGetValue(current_thread_tls_key);
#endif
      }
    }

    namespace
    {
#ifndef BOOST_HAS_THREADEX
// Windows CE doesn't define _beginthreadex

        struct ThreadProxyData
        {
            typedef unsigned (__stdcall* func)(void*);
            func start_address_;
            void* arglist_;
            ThreadProxyData(func start_address,void* arglist) : start_address_(start_address), arglist_(arglist) {}
        };

        DWORD WINAPI ThreadProxy(LPVOID args)
        {
            boost::csbl::unique_ptr<ThreadProxyData> data(reinterpret_cast<ThreadProxyData*>(args));
            DWORD ret=data->start_address_(data->arglist_);
            return ret;
        }

        inline uintptr_t _beginthreadex(void* security, unsigned stack_size, unsigned (__stdcall* start_address)(void*),
                                              void* arglist, unsigned initflag, unsigned* thrdaddr)
        {
            DWORD threadID;
            ThreadProxyData* data = new ThreadProxyData(start_address,arglist);
            HANDLE hthread=CreateThread(static_cast<LPSECURITY_ATTRIBUTES>(security),stack_size,ThreadProxy,
                                        data,initflag,&threadID);
            if (hthread==0) {
              delete data;
              return 0;
            }
            *thrdaddr=threadID;
            return reinterpret_cast<uintptr_t const>(hthread);
        }

#endif

    }

    namespace detail
    {
        struct thread_exit_callback_node
        {
            boost::detail::thread_exit_function_base* func;
            thread_exit_callback_node* next;

            thread_exit_callback_node(boost::detail::thread_exit_function_base* func_,
                                      thread_exit_callback_node* next_):
                func(func_),next(next_)
            {}
        };

    }

#if BOOST_PLAT_WINDOWS_RUNTIME
    namespace detail
    {
        std::atomic_uint threadCount;

        bool win32::scoped_winrt_thread::start(thread_func address, void *parameter, unsigned int *thrdId)
        {
            Microsoft::WRL::ComPtr<ABI::Windows::System::Threading::IThreadPoolStatics> threadPoolFactory;
            HRESULT hr = ::Windows::Foundation::GetActivationFactory(
                Microsoft::WRL::Wrappers::HStringReference(RuntimeClass_Windows_System_Threading_ThreadPool).Get(),
                &threadPoolFactory);
            if (hr != S_OK)
            {
                return false;
            }

            // Create event for tracking work item completion.
            *thrdId = ++threadCount;
            handle completionHandle = CreateEventExW(NULL, NULL, 0, EVENT_ALL_ACCESS);
            if (!completionHandle)
            {
                return false;
            }
            m_completionHandle = completionHandle;

            // Create new work item.
            Microsoft::WRL::ComPtr<ABI::Windows::System::Threading::IWorkItemHandler> workItem =
                Microsoft::WRL::Callback<Microsoft::WRL::Implements<Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>, ABI::Windows::System::Threading::IWorkItemHandler, Microsoft::WRL::FtmBase>>
                ([address, parameter, completionHandle](ABI::Windows::Foundation::IAsyncAction *)
            {
                // Add a reference since we need to access the completionHandle after the thread_start_function.
                // This is to handle cases where detach() was called and run_thread_exit_callbacks() would end
                // up closing the handle.
                ::boost::detail::thread_data_base* const thread_info(reinterpret_cast<::boost::detail::thread_data_base*>(parameter));
                intrusive_ptr_add_ref(thread_info);

                __try
                {
                    address(parameter);
                }
                __finally
                {
                    SetEvent(completionHandle);
                    intrusive_ptr_release(thread_info);
                }
                return S_OK;
            });

            // Schedule work item on the threadpool.
            Microsoft::WRL::ComPtr<ABI::Windows::Foundation::IAsyncAction> asyncAction;
            hr = threadPoolFactory->RunWithPriorityAndOptionsAsync(
                workItem.Get(),
                ABI::Windows::System::Threading::WorkItemPriority_Normal,
                ABI::Windows::System::Threading::WorkItemOptions_TimeSliced,
                &asyncAction);
            return hr == S_OK;
        }
    }
#endif

    namespace
    {
        void run_thread_exit_callbacks()
        {
            detail::thread_data_ptr current_thread_data(detail::get_current_thread_data(),false);
            if(current_thread_data)
            {
                while(! current_thread_data->tss_data.empty() || current_thread_data->thread_exit_callbacks)
                {
                    while(current_thread_data->thread_exit_callbacks)
                    {
                        detail::thread_exit_callback_node* const current_node=current_thread_data->thread_exit_callbacks;
                        current_thread_data->thread_exit_callbacks=current_node->next;
                        if(current_node->func)
                        {
                            (*current_node->func)();
                            boost::detail::heap_delete(current_node->func);
                        }
                        boost::detail::heap_delete(current_node);
                    }
                    while (!current_thread_data->tss_data.empty())
                    {
                        std::map<void const*,detail::tss_data_node>::iterator current
                            = current_thread_data->tss_data.begin();
                        if(current->second.func && (current->second.value!=0))
                        {
                            (*current->second.func)(current->second.value);
                        }
                        current_thread_data->tss_data.erase(current);
                    }
                }
                set_current_thread_data(0);
            }
        }

        unsigned __stdcall thread_start_function(void* param)
        {
            detail::thread_data_base* const thread_info(reinterpret_cast<detail::thread_data_base*>(param));
            set_current_thread_data(thread_info);
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
            BOOST_TRY
            {
#endif
                thread_info->run();
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
            }
            BOOST_CATCH(thread_interrupted const&)
            {
            }
            // Unhandled exceptions still cause the application to terminate
            BOOST_CATCH_END
#endif
            run_thread_exit_callbacks();
            return 0;
        }
    }

    thread::thread() BOOST_NOEXCEPT
    {}

    bool thread::start_thread_noexcept()
    {
#if BOOST_PLAT_WINDOWS_RUNTIME
         intrusive_ptr_add_ref(thread_info.get());
         if (!thread_info->thread_handle.start(&thread_start_function, thread_info.get(), &thread_info->id))
         {
             intrusive_ptr_release(thread_info.get());
             return false;
         }
         return true;
#else
        uintptr_t const new_thread=_beginthreadex(0,0,&thread_start_function,thread_info.get(),CREATE_SUSPENDED,&thread_info->id);
        if(!new_thread)
        {
            return false;
        }
        intrusive_ptr_add_ref(thread_info.get());
        thread_info->thread_handle=(detail::win32::handle)(new_thread);
        ResumeThread(thread_info->thread_handle);
        return true;
#endif
    }

    bool thread::start_thread_noexcept(const attributes& attr)
    {
#if BOOST_PLAT_WINDOWS_RUNTIME
        // Stack size isn't supported with Windows Runtime.
        attr;
        return start_thread_noexcept();
#else
      uintptr_t const new_thread=_beginthreadex(0,static_cast<unsigned int>(attr.get_stack_size()),&thread_start_function,thread_info.get(),
                                                CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_info->id);
      if(!new_thread)
      {
        return false;
      }
      intrusive_ptr_add_ref(thread_info.get());
      thread_info->thread_handle=(detail::win32::handle)(new_thread);
      ResumeThread(thread_info->thread_handle);
      return true;
#endif
    }

    thread::thread(detail::thread_data_ptr data):
        thread_info(data)
    {}

    namespace
    {
        struct externally_launched_thread:
            detail::thread_data_base
        {
            externally_launched_thread()
            {
                ++count;
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
                interruption_enabled=false;
#endif
            }
            ~externally_launched_thread() {
              BOOST_ASSERT(notify.empty());
              notify.clear();
//#ifndef BOOST_NO_EXCEPTIONS
              BOOST_ASSERT(async_states_.empty());
              async_states_.clear();
//#endif
            }

            void run()
            {}
            void notify_all_at_thread_exit(condition_variable*, mutex*)
            {}

        private:
            externally_launched_thread(externally_launched_thread&);
            void operator=(externally_launched_thread&);
        };

        void make_external_thread_data()
        {
            externally_launched_thread* me=detail::heap_new<externally_launched_thread>();
            BOOST_TRY
            {
                set_current_thread_data(me);
            }
            BOOST_CATCH(...)
            {
                detail::heap_delete(me);
                BOOST_RETHROW
            }
            BOOST_CATCH_END
        }

        detail::thread_data_base* get_or_make_current_thread_data()
        {
            detail::thread_data_base* current_thread_data(detail::get_current_thread_data());
            if(!current_thread_data)
            {
                make_external_thread_data();
                current_thread_data=detail::get_current_thread_data();
            }
            return current_thread_data;
        }
    }

    thread::id thread::get_id() const BOOST_NOEXCEPT
    {
#if defined BOOST_THREAD_PROVIDES_BASIC_THREAD_ID
        detail::thread_data_ptr local_thread_info=(get_thread_info)();
        if(!local_thread_info)
        {
            return 0;
        }
        return local_thread_info->id;
#else
        return thread::id((get_thread_info)());
#endif
    }

    bool thread::joinable() const BOOST_NOEXCEPT
    {
        detail::thread_data_ptr local_thread_info = (get_thread_info)();
        if(!local_thread_info)
        {
            return false;
        }
        return true;
    }
    bool thread::join_noexcept()
    {
        detail::thread_data_ptr local_thread_info=(get_thread_info)();
        if(local_thread_info)
        {
            this_thread::interruptible_wait(this->native_handle(), detail::internal_platform_timepoint::getMax());
            release_handle();
            return true;
        }
        else
        {
          return false;
        }
    }

    bool thread::do_try_join_until_noexcept(detail::internal_platform_timepoint const &timeout, bool& res)
    {
      detail::thread_data_ptr local_thread_info=(get_thread_info)();
      if(local_thread_info)
      {
          if(!this_thread::interruptible_wait(this->native_handle(), timeout))
          {
            res=false;
            return true;
          }
          release_handle();
          res=true;
          return true;
      }
      else
      {
        return false;
      }
    }

    void thread::detach()
    {
        release_handle();
    }

    void thread::release_handle()
    {
        thread_info=0;
    }

#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
    void thread::interrupt()
    {
        detail::thread_data_ptr local_thread_info=(get_thread_info)();
        if(local_thread_info)
        {
            local_thread_info->interrupt();
        }
    }

    bool thread::interruption_requested() const BOOST_NOEXCEPT
    {
        detail::thread_data_ptr local_thread_info=(get_thread_info)();
        return local_thread_info.get() && (winapi::WaitForSingleObjectEx(local_thread_info->interruption_handle,0,0)==0);
    }

#endif

    unsigned thread::hardware_concurrency() BOOST_NOEXCEPT
    {
        detail::win32::system_info info;
        detail::win32::get_system_info(&info);
        return info.dwNumberOfProcessors;
    }

    unsigned thread::physical_concurrency() BOOST_NOEXCEPT
    {
      // a bit too strict: Windows XP with SP3 would be sufficient
#if BOOST_PLAT_WINDOWS_RUNTIME                                    \
    || ( BOOST_USE_WINAPI_VERSION <= BOOST_WINAPI_VERSION_WINXP ) \
    || ( ( defined(__MINGW32__) && !defined(__MINGW64__) ) && _WIN32_WINNT < 0x0600)
        return 0;
#else
        unsigned cores = 0;
        DWORD size = 0;

        GetLogicalProcessorInformation(NULL, &size);
        if (ERROR_INSUFFICIENT_BUFFER != GetLastError())
            return 0;

        std::vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> buffer(size);
        if (GetLogicalProcessorInformation(&buffer.front(), &size) == FALSE)
            return 0;

        const size_t Elements = size / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);

        for (size_t i = 0; i < Elements; ++i) {
            if (buffer[i].Relationship == RelationProcessorCore)
                ++cores;
        }
        return cores;
#endif
    }

    thread::native_handle_type thread::native_handle()
    {
        detail::thread_data_ptr local_thread_info=(get_thread_info)();
        if(!local_thread_info)
        {
            return detail::win32::invalid_handle_value;
        }
#if BOOST_PLAT_WINDOWS_RUNTIME
        // There is no 'real' Win32 handle so we return a handle that at least can be waited on.
        return local_thread_info->thread_handle.waitable_handle();
#else
        return (detail::win32::handle)local_thread_info->thread_handle;
#endif
    }

    detail::thread_data_ptr thread::get_thread_info BOOST_PREVENT_MACRO_SUBSTITUTION () const
    {
        return thread_info;
    }

    namespace this_thread
    {
#ifndef UNDER_CE
#if !BOOST_PLAT_WINDOWS_RUNTIME
        namespace detail_
        {
            typedef struct _REASON_CONTEXT {
                ULONG Version;
                DWORD Flags;
                union {
                    LPWSTR SimpleReasonString;
                    struct {
                        HMODULE LocalizedReasonModule;
                        ULONG   LocalizedReasonId;
                        ULONG   ReasonStringCount;
                        LPWSTR  *ReasonStrings;
                    } Detailed;
                } Reason;
            } REASON_CONTEXT, *PREASON_CONTEXT;
            typedef BOOL (WINAPI *setwaitabletimerex_t)(HANDLE, const LARGE_INTEGER *, LONG, PTIMERAPCROUTINE, LPVOID, PREASON_CONTEXT, ULONG);
            static inline BOOL WINAPI SetWaitableTimerEx_emulation(HANDLE hTimer, const LARGE_INTEGER *lpDueTime, LONG lPeriod, PTIMERAPCROUTINE pfnCompletionRoutine, LPVOID lpArgToCompletionRoutine, PREASON_CONTEXT WakeContext, ULONG TolerableDelay)
            {
                return SetWaitableTimer(hTimer, lpDueTime, lPeriod, pfnCompletionRoutine, lpArgToCompletionRoutine, FALSE);
            }
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 6387) // MSVC sanitiser warns that GetModuleHandleA() might fail
#endif
            static inline setwaitabletimerex_t SetWaitableTimerEx()
            {
                static setwaitabletimerex_t setwaitabletimerex_impl;
                if(setwaitabletimerex_impl)
                    return setwaitabletimerex_impl;
                void (*addr)()=(void (*)()) GetProcAddress(
#if !defined(BOOST_NO_ANSI_APIS)
                    GetModuleHandleA("KERNEL32.DLL"),
#else
                    GetModuleHandleW(L"KERNEL32.DLL"),
#endif
                    "SetWaitableTimerEx");
                if(addr)
                    setwaitabletimerex_impl=(setwaitabletimerex_t) addr;
                else
                    setwaitabletimerex_impl=&SetWaitableTimerEx_emulation;
                return setwaitabletimerex_impl;
            }
#ifdef _MSC_VER
#pragma warning(pop)
#endif
        }
#endif
#endif
        bool interruptible_wait(detail::win32::handle handle_to_wait_for, detail::internal_platform_timepoint const &timeout)
        {
            detail::win32::handle handles[4]={0};
            unsigned handle_count=0;
            unsigned wait_handle_index=~0U;
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
            unsigned interruption_index=~0U;
#endif
            unsigned timeout_index=~0U;
            if(handle_to_wait_for!=detail::win32::invalid_handle_value)
            {
                wait_handle_index=handle_count;
                handles[handle_count++]=handle_to_wait_for;
            }
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
            if(detail::get_current_thread_data() && detail::get_current_thread_data()->interruption_enabled)
            {
                interruption_index=handle_count;
                handles[handle_count++]=detail::get_current_thread_data()->interruption_handle;
            }
#endif
            detail::win32::handle_manager timer_handle;

#ifndef UNDER_CE
#if !BOOST_PLAT_WINDOWS_RUNTIME
            // Preferentially use coalescing timers for better power consumption and timer accuracy
            if(timeout != detail::internal_platform_timepoint::getMax())
            {
                boost::intmax_t const time_left_msec = (timeout - detail::internal_platform_clock::now()).getMs();
                timer_handle=CreateWaitableTimer(NULL,false,NULL);
                if(timer_handle!=0)
                {
                    ULONG tolerable=32; // Empirical testing shows Windows ignores this when <= 26
                    if(time_left_msec/20>tolerable)  // 5%
                        tolerable=static_cast<ULONG>(time_left_msec/20);
                    LARGE_INTEGER due_time={{0,0}};
                    if(time_left_msec>0)
                    {
                        due_time.QuadPart=-(time_left_msec*10000); // negative indicates relative time
                    }
                    bool const set_time_succeeded=detail_::SetWaitableTimerEx()(timer_handle,&due_time,0,0,0,NULL,tolerable)!=0;
                    if(set_time_succeeded)
                    {
                        timeout_index=handle_count;
                        handles[handle_count++]=timer_handle;
                    }
                }
            }
#endif
#endif

            bool const using_timer=timeout_index!=~0u;
            boost::intmax_t time_left_msec(INFINITE);
            if(!using_timer && timeout != detail::internal_platform_timepoint::getMax())
            {
                time_left_msec = (timeout - detail::internal_platform_clock::now()).getMs();
                if(time_left_msec < 0)
                {
                    time_left_msec = 0;
                }
            }

            do
            {
                if(handle_count)
                {
                    unsigned long const notified_index=winapi::WaitForMultipleObjectsEx(handle_count,handles,false,static_cast<DWORD>(time_left_msec), 0);
                    if(notified_index<handle_count)
                    {
                        if(notified_index==wait_handle_index)
                        {
                            return true;
                        }
#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
                        else if(notified_index==interruption_index)
                        {
                            winapi::ResetEvent(detail::get_current_thread_data()->interruption_handle);
                            throw thread_interrupted();
                        }
#endif
                        else if(notified_index==timeout_index)
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    detail::win32::sleep(static_cast<unsigned long>(time_left_msec));
                }

                if(!using_timer && timeout != detail::internal_platform_timepoint::getMax())
                {
                    time_left_msec = (timeout - detail::internal_platform_clock::now()).getMs();
                }
            }
            while(time_left_msec == INFINITE || time_left_msec > 0);
            return false;
        }

        namespace no_interruption_point
        {
        bool non_interruptible_wait(detail::win32::handle handle_to_wait_for, detail::internal_platform_timepoint const &timeout)
        {
            detail::win32::handle handles[3]={0};
            unsigned handle_count=0;
            unsigned wait_handle_index=~0U;
            unsigned timeout_index=~0U;
            if(handle_to_wait_for!=detail::win32::invalid_handle_value)
            {
                wait_handle_index=handle_count;
                handles[handle_count++]=handle_to_wait_for;
            }
            detail::win32::handle_manager timer_handle;

#ifndef UNDER_CE
#if !BOOST_PLAT_WINDOWS_RUNTIME
            // Preferentially use coalescing timers for better power consumption and timer accuracy
            if(timeout != detail::internal_platform_timepoint::getMax())
            {
                boost::intmax_t const time_left_msec = (timeout - detail::internal_platform_clock::now()).getMs();
                timer_handle=CreateWaitableTimer(NULL,false,NULL);
                if(timer_handle!=0)
                {
                    ULONG tolerable=32; // Empirical testing shows Windows ignores this when <= 26
                    if(time_left_msec/20>tolerable)  // 5%
                        tolerable=static_cast<ULONG>(time_left_msec/20);
                    LARGE_INTEGER due_time={{0,0}};
                    if(time_left_msec>0)
                    {
                        due_time.QuadPart=-(time_left_msec*10000); // negative indicates relative time
                    }
                    bool const set_time_succeeded=detail_::SetWaitableTimerEx()(timer_handle,&due_time,0,0,0,NULL,tolerable)!=0;
                    if(set_time_succeeded)
                    {
                        timeout_index=handle_count;
                        handles[handle_count++]=timer_handle;
                    }
                }
            }
#endif
#endif

            bool const using_timer=timeout_index!=~0u;
            boost::intmax_t time_left_msec(INFINITE);
            if(!using_timer && timeout != detail::internal_platform_timepoint::getMax())
            {
                time_left_msec = (timeout - detail::internal_platform_clock::now()).getMs();
                if(time_left_msec < 0)
                {
                    time_left_msec = 0;
                }
            }

            do
            {
                if(handle_count)
                {
                    unsigned long const notified_index=winapi::WaitForMultipleObjectsEx(handle_count,handles,false,static_cast<DWORD>(time_left_msec), 0);
                    if(notified_index<handle_count)
                    {
                        if(notified_index==wait_handle_index)
                        {
                            return true;
                        }
                        else if(notified_index==timeout_index)
                        {
                            return false;
                        }
                    }
                }
                else
                {
                    detail::win32::sleep(static_cast<unsigned long>(time_left_msec));
                }

                if(!using_timer && timeout != detail::internal_platform_timepoint::getMax())
                {
                    time_left_msec = (timeout - detail::internal_platform_clock::now()).getMs();
                }
            }
            while(time_left_msec == INFINITE || time_left_msec > 0);
            return false;
        }
        }

        thread::id get_id() BOOST_NOEXCEPT
        {
#if defined BOOST_THREAD_PROVIDES_BASIC_THREAD_ID
#if BOOST_PLAT_WINDOWS_RUNTIME
            detail::thread_data_base* current_thread_data(detail::get_current_thread_data());
            if (current_thread_data)
            {
                return current_thread_data->id;
            }
#endif
            return winapi::GetCurrentThreadId();
#else
            return thread::id(get_or_make_current_thread_data());
#endif
        }

#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
        void interruption_point()
        {
            if(interruption_enabled() && interruption_requested())
            {
                winapi::ResetEvent(detail::get_current_thread_data()->interruption_handle);
                throw thread_interrupted();
            }
        }

        bool interruption_enabled() BOOST_NOEXCEPT
        {
            return detail::get_current_thread_data() && detail::get_current_thread_data()->interruption_enabled;
        }

        bool interruption_requested() BOOST_NOEXCEPT
        {
            return detail::get_current_thread_data() && (winapi::WaitForSingleObjectEx(detail::get_current_thread_data()->interruption_handle,0,0)==0);
        }
#endif

        void yield() BOOST_NOEXCEPT
        {
            detail::win32::sleep(0);
        }

#if defined BOOST_THREAD_PROVIDES_INTERRUPTIONS
        disable_interruption::disable_interruption() BOOST_NOEXCEPT:
            interruption_was_enabled(interruption_enabled())
        {
            if(interruption_was_enabled)
            {
                detail::get_current_thread_data()->interruption_enabled=false;
            }
        }

        disable_interruption::~disable_interruption() BOOST_NOEXCEPT
        {
            if(detail::get_current_thread_data())
            {
                detail::get_current_thread_data()->interruption_enabled=interruption_was_enabled;
            }
        }

        restore_interruption::restore_interruption(disable_interruption& d) BOOST_NOEXCEPT
        {
            if(d.interruption_was_enabled)
            {
                detail::get_current_thread_data()->interruption_enabled=true;
            }
        }

        restore_interruption::~restore_interruption() BOOST_NOEXCEPT
        {
            if(detail::get_current_thread_data())
            {
                detail::get_current_thread_data()->interruption_enabled=false;
            }
        }
#endif
    }

    namespace detail
    {
        void add_thread_exit_function(thread_exit_function_base* func)
        {
            detail::thread_data_base* const current_thread_data(get_or_make_current_thread_data());
            thread_exit_callback_node* const new_node=
                heap_new<thread_exit_callback_node>(
                    func,current_thread_data->thread_exit_callbacks);
            current_thread_data->thread_exit_callbacks=new_node;
        }

        tss_data_node* find_tss_data(void const* key)
        {
            detail::thread_data_base* const current_thread_data(get_current_thread_data());
            if(current_thread_data)
            {
                std::map<void const*,tss_data_node>::iterator current_node=
                    current_thread_data->tss_data.find(key);
                if(current_node!=current_thread_data->tss_data.end())
                {
                    return &current_node->second;
                }
            }
            return NULL;
        }

        void* get_tss_data(void const* key)
        {
            if(tss_data_node* const current_node=find_tss_data(key))
            {
                return current_node->value;
            }
            return NULL;
        }

        void add_new_tss_node(void const* key,
                              boost::shared_ptr<tss_cleanup_function> func,
                              void* tss_data)
        {
            detail::thread_data_base* const current_thread_data(get_or_make_current_thread_data());
            current_thread_data->tss_data.insert(std::make_pair(key,tss_data_node(func,tss_data)));
        }

        void erase_tss_node(void const* key)
        {
            detail::thread_data_base* const current_thread_data(get_or_make_current_thread_data());
            current_thread_data->tss_data.erase(key);
        }

        void set_tss_data(void const* key,
                          boost::shared_ptr<tss_cleanup_function> func,
                          void* tss_data,bool cleanup_existing)
        {
            if(tss_data_node* const current_node=find_tss_data(key))
            {
                if(cleanup_existing && current_node->func && (current_node->value!=0))
                {
                    (*current_node->func)(current_node->value);
                }
                if(func || (tss_data!=0))
                {
                    current_node->func=func;
                    current_node->value=tss_data;
                }
                else
                {
                    erase_tss_node(key);
                }
            }
            else if(func || (tss_data!=0))
            {
                add_new_tss_node(key,func,tss_data);
            }
        }
    }

    BOOST_THREAD_DECL void __cdecl on_process_enter()
    {}

    BOOST_THREAD_DECL void __cdecl on_thread_enter()
    {}

    BOOST_THREAD_DECL void __cdecl on_process_exit()
    {
        boost::cleanup_tls_key();
    }

    BOOST_THREAD_DECL void __cdecl on_thread_exit()
    {
        boost::run_thread_exit_callbacks();
    }

    BOOST_THREAD_DECL void notify_all_at_thread_exit(condition_variable& cond, unique_lock<mutex> lk)
    {
      detail::thread_data_base* const current_thread_data(detail::get_current_thread_data());
      if(current_thread_data)
      {
        current_thread_data->notify_all_at_thread_exit(&cond, lk.release());
      }
    }
}