-
Notifications
You must be signed in to change notification settings - Fork 47
/
concrt.h
executable file
·5755 lines (5064 loc) · 236 KB
/
concrt.h
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
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***
* ==++==
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* ==--==
* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
*
* concrt.h
*
* Main public header file for ConcRT. This is the only header file a C++ program must include to use the core concurrency runtime features.
*
* The Agents And Message Blocks Library and the Parallel Patterns Library (PPL) are defined in separate header files.
* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
****/
#pragma once
#include <crtdefs.h>
#if defined(_CRT_WINDOWS)
#error Must not be included during CRT build with _CRT_WINDOWS flag enabled
#endif
#if !(defined (_M_X64) || defined (_M_IX86) || defined (_M_ARM) || defined (_M_ARM64))
#error ERROR: Concurrency Runtime is supported only on X64, X86, ARM, and ARM64 architectures.
#endif /* !(defined (_M_X64) || defined (_M_IX86) || defined (_M_ARM) || defined (_M_ARM64)) */
#if defined (_M_CEE)
#error ERROR: Concurrency Runtime is not supported when compiling /clr.
#endif /* defined (_M_CEE) */
#ifndef __cplusplus
#error ERROR: Concurrency Runtime is supported only for C++.
#endif /* __cplusplus */
#define _CONCRT_H
#include <exception>
#include <sal.h>
#include <limits.h>
#include <crtdbg.h>
#include <guiddef.h>
#include <intrin.h>
#include <new>
#include <pplinterface.h>
#pragma pack(push,_CRT_PACKING)
#pragma warning(push,_STL_WARNING_LEVEL)
#pragma warning(disable: _STL_DISABLED_WARNINGS)
_STL_DISABLE_CLANG_WARNINGS
#pragma push_macro("new")
#undef new
// Forward declare structs needed from Windows header files
struct _SECURITY_ATTRIBUTES;
typedef _SECURITY_ATTRIBUTES* LPSECURITY_ATTRIBUTES;
struct _GROUP_AFFINITY;
typedef _GROUP_AFFINITY* PGROUP_AFFINITY;
// Define essential types needed from Windows header files
typedef unsigned long DWORD;
#ifndef _HRESULT_DEFINED
#define _HRESULT_DEFINED
#ifdef __midl
typedef LONG HRESULT;
#else /* __midl */
typedef _Return_type_success_(return >= 0) long HRESULT;
#endif /* __midl */
#endif /* _HRESULT_DEFINED */
typedef void * HANDLE;
#pragma push_macro("_YieldProcessor")
#undef _YieldProcessor
#if (defined (_M_IX86) || defined (_M_X64)) && !defined(_M_HYBRID) && !defined(_M_ARM64EC)
#define _YieldProcessor _mm_pause
#else
inline void _YieldProcessor() {}
#endif
#if (defined (_M_IX86) || defined (_M_ARM))
#define _InterlockedIncrementSizeT(_Target) static_cast<size_t>(_InterlockedIncrement(reinterpret_cast<long volatile *>(_Target)))
#define _InterlockedDecrementSizeT(_Target) static_cast<size_t>(_InterlockedDecrement(reinterpret_cast<long volatile *>(_Target)))
#define _InterlockedCompareExchangeSizeT(_Target, _Exchange, _Comparand) static_cast<size_t>(_InterlockedCompareExchange( \
reinterpret_cast<long volatile *>(_Target), \
static_cast<long>(_Exchange), \
static_cast<long>(_Comparand)))
typedef unsigned long DWORD_PTR, *PDWORD_PTR;
#else /* (defined (_M_IX86) || defined (_M_ARM)) */
#define _InterlockedIncrementSizeT(_Target) static_cast<size_t>(_InterlockedIncrement64(reinterpret_cast<__int64 volatile *>(_Target)))
#define _InterlockedDecrementSizeT(_Target) static_cast<size_t>(_InterlockedDecrement64(reinterpret_cast<__int64 volatile *>(_Target)))
#define _InterlockedCompareExchangeSizeT(_Target, _Exchange, _Comparand) static_cast<size_t>(_InterlockedCompareExchange64( \
reinterpret_cast<__int64 volatile *>(_Target), \
static_cast<__int64>(_Exchange), \
static_cast<__int64>(_Comparand)))
typedef unsigned __int64 DWORD_PTR, *PDWORD_PTR;
#endif /* (defined (_M_IX86) || defined (_M_ARM)) */
#ifdef _DEBUG
#ifdef _MSC_VER
// Turn off compiler warnings that are exacerbated by constructs in this
// file's definitions:
// Warning C4127: conditional expression is constant. This is caused by
// the macros with "do { ... } while (false)" syntax. The syntax is
// a good way to ensure that a statement-like macro can be used in all
// contexts (specifically if statements), but the compiler warns about
// the "while (false)" part.
#define _CONCRT_ASSERT(x) __pragma (warning (suppress: 4127)) do {_ASSERTE(x); __assume(x);} while(false)
#else /* _MSC_VER */
#define _CONCRT_ASSERT(x) do {_ASSERTE(x); __assume(x);} while(false)
#endif /* _MSC_VER */
#else /* _DEBUG */
#define _CONCRT_ASSERT(x) __assume(x)
#endif /* _DEBUG */
// Used internally to represent the smallest unit in which to allocate hidden types
typedef void * _CONCRT_BUFFER;
#define _LISTENTRY_SIZE ((2 * sizeof(void *) + sizeof(_CONCRT_BUFFER) - 1) / sizeof(_CONCRT_BUFFER))
#define _SAFERWLIST_SIZE ((3 * sizeof(void *) + 2 * sizeof(long) + sizeof(_CONCRT_BUFFER) - 1) / sizeof(_CONCRT_BUFFER))
/// <summary>
/// The <c>Concurrency</c> namespace provides classes and functions that access the Concurrency Runtime,
/// a concurrent programming framework for C++. For more information, see <see cref="Concurrency Runtime"/>.
/// </summary>
/**/
namespace Concurrency
{
/// <summary>
/// Pauses the current context for a specified amount of time.
/// </summary>
/// <param name="_Milliseconds">
/// The number of milliseconds the current context should be paused for. If the <paramref name="_Milliseconds"/> parameter is set to
/// the value <c>0</c>, the current context should yield execution to other runnable contexts before continuing.
/// </param>
/// <remarks>
/// If this method is called on a Concurrency Runtime scheduler context, the scheduler will find a different context to run on the underlying
/// resource. Because the scheduler is cooperative in nature, this context cannot resume exactly after the number of milliseconds specified.
/// If the scheduler is busy executing other tasks that do not cooperatively yield to the scheduler, the wait period could be
/// indefinite.
/// </remarks>
/**/
_CONCRTIMP void __cdecl wait(unsigned int _Milliseconds);
/// <summary>
/// Allocates a block of memory of the size specified from the Concurrency Runtime Caching Suballocator.
/// </summary>
/// <param name="_NumBytes">
/// The number of bytes of memory to allocate.
/// </param>
/// <returns>
/// A pointer to newly allocated memory.
/// </returns>
/// <remarks>
/// For more information about which scenarios in your application could benefit from using the Caching Suballocator,
/// see <see cref="Task Scheduler (Concurrency Runtime)"/>.
/// </remarks>
/// <seealso cref="Concurrency::Free Function"/>
/**/
_CONCRTIMP void * __cdecl Alloc(size_t _NumBytes);
/// <summary>
/// Releases a block of memory previously allocated by the <c>Alloc</c> method to the Concurrency Runtime Caching Suballocator.
/// </summary>
/// <param name="_PAllocation">
/// A pointer to memory previously allocated by the <c>Alloc</c> method which is to be freed. If the parameter <paramref name="_PAllocation"/>
/// is set to the value <c>NULL</c>, this method will ignore it and return immediately.
/// </param>
/// <remarks>
/// For more information about which scenarios in your application could benefit from using the Caching Suballocator,
/// see <see cref="Task Scheduler (Concurrency Runtime)"/>.
/// </remarks>
/// <seealso cref="Concurrency::Alloc Function"/>
/**/
_CONCRTIMP void __cdecl Free(_Pre_maybenull_ _Post_invalid_ void * _PAllocation);
/// <summary>
/// Concurrency::details contains definitions of support routines in the public namespaces and one or more macros.
/// Users should not directly interact with this internal namespace.
/// </summary>
/**/
#if defined(_CRT_USE_WINAPI_FAMILY_DESKTOP_APP) || defined(_XBOX_ONE)
/// <summary>
/// Restricts the execution resources used by the Concurrency Runtime internal worker threads to the affinity set specified.
/// <para> It is valid to call this method only before the Resource Manager has been created, or between two Resource Manager lifetimes.
/// It can be invoked multiple times as long as the Resource Manager does not exist at the time of invocation. After an affinity limit
/// has been set, it remains in effect until the next valid call to the <c>set_task_execution_resources</c> method.</para>
/// <para>The affinity mask provided need not be a subset of the process affinity mask. The process affinity will be updated if necessary.</para>
/// </summary>
/// <param name="_ProcessAffinityMask">
/// The affinity mask that the Concurrency Runtime worker threads are to be restricted to. Use this method on a system with greater than 64
/// hardware threads only if you want to limit the Concurrency Runtime to a subset of the current processor group. In general, you should
/// use the version of the method that accepts an array of group affinities as a parameter, to restrict affinity on machines with greater
/// than 64 hardware threads.
/// </param>
/// <remarks>
/// The method will throw an <see cref="invalid_operation Class">invalid_operation </see> exception if a Resource Manager is present at
/// the time it is invoked, and an <see cref="invalid_argument">invalid_argument </see> exception if the affinity specified results in an empty set of resources.
/// <para>The version of the method that takes an array of group affinities as a parameter should only be used on operating systems with version
/// Windows 7 or higher. Otherwise, an <see cref="invalid_operation Class">invalid_operation </see> exception is thrown.</para>
/// <para>Programatically modifying the process affinity after this method has been invoked will not cause the Resource Manager to re-evaluate
/// the affinity it is restricted to. Therefore, all changes to process affinity should be made before calling this method.</para>
/// </remarks>
/**/
_CONCRTIMP void __cdecl set_task_execution_resources(DWORD_PTR _ProcessAffinityMask);
#endif /* defined(_CRT_USE_WINAPI_FAMILY_DESKTOP_APP) || defined(_XBOX_ONE) */
#ifdef _CRT_USE_WINAPI_FAMILY_DESKTOP_APP
/// <summary>
/// Restricts the execution resources used by the Concurrency Runtime internal worker threads to the affinity set specified.
/// <para> It is valid to call this method only before the Resource Manager has been created, or between two Resource Manager lifetimes.
/// It can be invoked multiple times as long as the Resource Manager does not exist at the time of invocation. After an affinity limit
/// has been set, it remains in effect until the next valid call to the <c>set_task_execution_resources</c> method.</para>
/// <para>The affinity mask provided need not be a subset of the process affinity mask. The process affinity will be updated if necessary.</para>
/// </summary>
/// <param name="_Count">
/// The number of <c>GROUP_AFFINITY</c> entries in the array specified by the parameter <paramref name="_PGroupAffinity"/>.
/// </param>
/// <param name="_PGroupAffinity">
/// An array of <c>GROUP_AFFINITY</c> entries.
/// </param>
/// <remarks>
/// The method will throw an <see cref="invalid_operation Class">invalid_operation </see> exception if a Resource Manager is present at
/// the time it is invoked, and an <see cref="invalid_argument">invalid_argument </see> exception if the affinity specified results in an empty set of resources.
/// <para>The version of the method that takes an array of group affinities as a parameter should only be used on operating systems with version
/// Windows 7 or higher. Otherwise, an <see cref="invalid_operation Class">invalid_operation </see> exception is thrown.</para>
/// <para>Programatically modifying the process affinity after this method has been invoked will not cause the Resource Manager to re-evaluate
/// the affinity it is restricted to. Therefore, all changes to process affinity should be made before calling this method.</para>
/// </remarks>
/**/
_CONCRTIMP void __cdecl set_task_execution_resources(unsigned short _Count, PGROUP_AFFINITY _PGroupAffinity);
#endif /* _CRT_USE_WINAPI_FAMILY_DESKTOP_APP */
/// <summary>
/// An elementary abstraction for a task, defined as <c>void (__cdecl * TaskProc)(void *)</c>. A <c>TaskProc</c> is called to
/// invoke the body of a task.
/// </summary>
/**/
typedef void (__cdecl * TaskProc)(void *);
//
// Forward declarations:
//
class Scheduler;
class ScheduleGroup;
class Context;
namespace details
{
//
// Forward declarations:
//
class ContextBase;
class _TaskCollectionBase;
//
// A utility to hide operator delete from certain objects while still allowing the runtime to delete them internally.
//
template<class _Ty>
void _InternalDeleteHelper(_Ty * _PObject)
{
delete _PObject;
}
// The purpose of the class is solely to direct allocations of ConcRT classes
// through a single point, using an internal allocator.
struct _AllocBase
{
// Standard operator new
void * operator new(size_t _Size)
{
return ::Concurrency::Alloc(_Size);
}
// Standard operator delete
void operator delete(void * _Ptr) noexcept
{
::Concurrency::Free(_Ptr);
}
// Standard operator new, no-throw version
void * operator new(size_t _Size, const ::std::nothrow_t&) noexcept
{
void * _Ptr;
try
{
_Ptr = ::Concurrency::Alloc(_Size);
}
catch(...)
{
_Ptr = nullptr;
}
return (_Ptr);
}
// Standard operator delete, no-throw version
void operator delete(void * _Ptr, const ::std::nothrow_t&) noexcept
{
operator delete(_Ptr);
}
// Standard operator new array
void * operator new[](size_t _Size)
{
return operator new(_Size);
}
// Standard operator delete array
void operator delete[](void * _Ptr) noexcept
{
operator delete(_Ptr);
}
// Standard operator new array, no-throw version
void * operator new[](size_t _Size, const ::std::nothrow_t& _No_throw) noexcept
{
return operator new(_Size, _No_throw);
}
// Standard operator delete array, no-throw version
void operator delete[](void * _Ptr, const ::std::nothrow_t& _No_throw) noexcept
{
operator delete(_Ptr, _No_throw);
}
// Standard operator new with void* placement
void * operator new(size_t, void * _Location) noexcept
{
return _Location;
}
// Standard operator delete with void* placement
void operator delete(void *, void *) noexcept
{
}
// Standard operator new array with void* placement
void * __cdecl operator new[](size_t, void * _Location) noexcept
{
return _Location;
}
// Standard operator delete array with void* placement
void __cdecl operator delete[](void *, void *) noexcept
{
}
};
// Stubs to allow the header files to access runtime functionality for WINAPI_PARTITION apps.
class _Context
{
public:
_CONCRTIMP _Context(::Concurrency::Context * _PContext = nullptr) : _M_pContext(_PContext) {}
_CONCRTIMP static _Context __cdecl _CurrentContext();
_CONCRTIMP static void __cdecl _Yield();
_CONCRTIMP static void __cdecl _Oversubscribe(bool _BeginOversubscription);
_CONCRTIMP bool _IsSynchronouslyBlocked() const;
private:
::Concurrency::Context * _M_pContext;
};
class _Scheduler
{
public:
_CONCRTIMP _Scheduler(::Concurrency::Scheduler * _PScheduler = nullptr) : _M_pScheduler(_PScheduler) {}
_CONCRTIMP unsigned int _Reference();
_CONCRTIMP unsigned int _Release();
_CONCRTIMP ::Concurrency::Scheduler * _GetScheduler() { return _M_pScheduler; }
private:
::Concurrency::Scheduler * _M_pScheduler;
};
class _CurrentScheduler
{
public:
_CONCRTIMP static void __cdecl _ScheduleTask(TaskProc _Proc, void * _Data);
_CONCRTIMP static unsigned int __cdecl _Id();
_CONCRTIMP static unsigned int __cdecl _GetNumberOfVirtualProcessors();
_CONCRTIMP static _Scheduler __cdecl _Get();
};
//
// Wrappers for atomic access
//
template <size_t _Size>
struct _Subatomic_impl { };
template<>
struct _Subatomic_impl<4> {
template <typename _Ty>
static void _StoreWithRelease(volatile _Ty& _Location, _Ty _Rhs) {
// For the compiler, a volatile write has release semantics. In addition, on ARM,
// the volatile write will emit a data memory barrier before the write.
_Location = _Rhs;
}
template <typename _Ty>
static _Ty _LoadWithAquire(volatile _Ty& _Location) {
// For the compiler, a volatile read has acquire semantics. In addition, on ARM,
// the volatile read will emit a data memory barrier after the read.
return _Location;
}
template <typename _Ty>
static _Ty _CompareAndSwap(volatile _Ty& _Location, _Ty _NewValue, _Ty _Comperand) {
return (_Ty)_InterlockedCompareExchange((volatile long*)&_Location, (long)_NewValue, (long)_Comperand);
}
template <typename _Ty>
static _Ty _FetchAndAdd(volatile _Ty& _Location, _Ty _Addend) {
return (_Ty)_InterlockedExchangeAdd((volatile long*)&_Location, (long)_Addend);
}
template <typename _Ty>
static _Ty _Increment(volatile _Ty& _Location) {
return (_Ty)_InterlockedIncrement((volatile long*)&_Location);
}
template <typename _Ty>
static _Ty _Decrement(volatile _Ty& _Location) {
return (_Ty)_InterlockedDecrement((volatile long*)&_Location);
}
};
#if defined (_WIN64)
template<>
struct _Subatomic_impl<8> {
template <typename _Ty>
static void _StoreWithRelease(volatile _Ty& _Location, _Ty _Rhs) {
// For the compiler, a volatile write has release semantics.
_Location = _Rhs;
}
template <typename _Ty>
static _Ty _LoadWithAquire(volatile _Ty& _Location) {
// For the compiler, a volatile read has acquire semantics.
return _Location;
}
template <typename _Ty>
static _Ty _CompareAndSwap(volatile _Ty& _Location, _Ty _NewValue, _Ty _Comperand) {
return (_Ty)_InterlockedCompareExchange64((volatile __int64*)&_Location, (__int64)_NewValue, (__int64)_Comperand);
}
template <typename _Ty>
static _Ty _FetchAndAdd(volatile _Ty& _Location, _Ty _Addend) {
return (_Ty)_InterlockedExchangeAdd64((volatile __int64*)&_Location, (__int64)_Addend);
}
template <typename _Ty>
static _Ty _Increment(volatile _Ty& _Location) {
return (_Ty)_InterlockedIncrement64((volatile __int64*)&_Location);
}
template <typename _Ty>
static _Ty _Decrement(volatile _Ty& _Location) {
return (_Ty)_InterlockedDecrement64((volatile __int64*)&_Location);
}
};
#endif /* defined (_M_X64) */
//
// Wrapper for atomic access. Only works for 4-byte or 8-byte types (for example, int, long, long long, size_t, pointer).
// Anything else might fail to compile.
//
template <typename _Ty>
class _Subatomic {
private:
volatile _Ty _M_value;
public:
operator _Ty() const volatile {
return _Subatomic_impl<sizeof(_Ty)>::_LoadWithAquire(_M_value);
}
_Ty operator=(_Ty _Rhs) {
_Subatomic_impl<sizeof(_Ty)>::_StoreWithRelease(_M_value, _Rhs);
return _Rhs;
}
_Ty _CompareAndSwap(_Ty _NewValue, _Ty _Comperand) {
return _Subatomic_impl<sizeof(_Ty)>::_CompareAndSwap(_M_value, _NewValue, _Comperand);
}
_Ty _FetchAndAdd(_Ty _Addend) {
return _Subatomic_impl<sizeof(_Ty)>::_FetchAndAdd(_M_value, _Addend);
}
_Ty operator++() {
return _Subatomic_impl<sizeof(_Ty)>::_Increment(_M_value);
}
_Ty operator++(int) {
return _Subatomic_impl<sizeof(_Ty)>::_Increment(_M_value) - 1;
}
_Ty operator--() {
return _Subatomic_impl<sizeof(_Ty)>::_Decrement(_M_value);
}
_Ty operator--(int) {
return _Subatomic_impl<sizeof(_Ty)>::_Decrement(_M_value) + 1;
}
_Ty operator+=(_Ty _Addend) {
return _FetchAndAdd(_Addend) + _Addend;
}
};
//
// An RAII class that spin-waits on a "rented" flag.
//
class _SpinLock
{
private:
volatile long& _M_flag;
public:
_CONCRTIMP _SpinLock(volatile long& _Flag);
_CONCRTIMP ~_SpinLock();
private:
_SpinLock(const _SpinLock&);
void operator=(const _SpinLock&);
};
//
// A class that holds the count used for spinning and is dependent
// on the number of hardware threads
//
struct _SpinCount
{
// Initializes the spinCount to either 0 or SPIN_COUNT, depending on
// the number of hardware threads.
static void __cdecl _Initialize();
// Returns the current value of s_spinCount
_CONCRTIMP static unsigned int __cdecl _Value();
// The number of iterations used for spinning
static unsigned int _S_spinCount;
};
/// <summary>
/// Default method for yielding during a spin wait
/// </summary>
/**/
void _CONCRTIMP __cdecl _UnderlyingYield();
/// <summary>
/// Returns the hardware concurrency available to the Concurrency Runtime, taking into account process affinity, or any restrictions
/// in place because of the set_task_execution_resources method.
/// </summary>
/**/
unsigned int _CONCRTIMP __cdecl _GetConcurrency();
/// <summary>
/// Implements busy wait with no backoff
/// </summary>
/**/
template<unsigned int _YieldCount = 1>
class _CONCRTIMP _SpinWait
{
public:
typedef void (__cdecl *_YieldFunction)();
/// <summary>
/// Construct a spin wait object
/// </summary>
/**/
_SpinWait(_YieldFunction _YieldMethod = _UnderlyingYield)
: _M_state(_StateInitial), _M_yieldFunction(_YieldMethod)
{
// Defer initialization of other fields to _SpinOnce().
}
/// <summary>
/// Set a dynamic spin count.
/// </summary>
/**/
void _SetSpinCount(unsigned int _Count)
{
_CONCRT_ASSERT(_M_state == _StateInitial);
if (_Count == 0)
{
// Specify a count of 0 if we are on a single proc.
_M_state = _StateSingle;
}
else
{
_M_currentSpin = _Count;
_M_currentYield = _YieldCount;
_M_state = _StateSpin;
}
}
/// <summary>
/// Spins for one time quantum,until a maximum spin is reached.
/// </summary>
/// <returns>
/// false if spin count has reached steady state, true otherwise.
/// </returns>
/// <remarks>
/// If the spin count is not changing do not spin again
/// because there is either only one processor, or the maximum spin has been reached and blocking is
/// probably a better solution. However, if called again, SpinOnce will spin for a maximum spin count.
/// </remarks>
/**/
bool _SpinOnce()
{
switch (_M_state)
{
case _StateSpin:
{
unsigned long _Count = _NumberOfSpins();
for (unsigned long _I = 0; _I < _Count; _I++)
{
_YieldProcessor();
}
if (!_ShouldSpinAgain())
{
_M_state = (_M_currentYield == 0) ? _StateBlock : _StateYield;
}
return true;
}
case _StateYield:
_CONCRT_ASSERT(_M_currentYield > 0);
if (--_M_currentYield == 0)
{
_M_state = _StateBlock;
}
// Execute the yield
_DoYield();
return true;
case _StateBlock:
// Reset to defaults if client does not block
_Reset();
return false;
case _StateSingle:
// No need to spin on a single processor: just execute the yield
_DoYield();
return false;
case _StateInitial:
// Reset counters to their default value and Spin once.
_Reset();
return _SpinOnce();
default:
// Unreached
return false;
};
}
protected:
/// <summary>
/// State of the spin wait class.
/// </summary>
/**/
enum _SpinState
{
_StateInitial,
_StateSpin,
_StateYield,
_StateBlock,
_StateSingle
};
/// <summary>
/// Yields its time slice using the specified yieldFunction
/// </summary>
/**/
void _DoYield()
{
constexpr bool _ShouldYield = (_YieldCount != 0);
if constexpr (_ShouldYield)
{
_CONCRT_ASSERT(_M_yieldFunction != nullptr);
_M_yieldFunction();
}
else
{
_YieldProcessor();
}
}
/// <summary>
/// Resets the counts and state to the default.
/// </summary>
/**/
void _Reset()
{
_M_state = _StateInitial;
// Reset to the default spin value. The value specified
// by the client is ignored on a reset.
_SetSpinCount(_SpinCount::_Value());
_CONCRT_ASSERT(_M_state != _StateInitial);
}
/// <summary>
/// Determines the current spin count
/// </summary>
/// <returns>
/// The number of spins to execute for this iteration
/// </returns>
/**/
unsigned long _NumberOfSpins()
{
return 1;
}
/// <summary>
/// Determines whether maximum spin has been reached
/// </summary>
/// <returns>
/// false if spin count has reached steady state, true otherwise.
/// </returns>
/**/
bool _ShouldSpinAgain()
{
return (--_M_currentSpin > 0);
}
unsigned long _M_currentSpin{};
unsigned long _M_currentYield{};
_SpinState _M_state;
_YieldFunction _M_yieldFunction;
};
typedef _SpinWait<> _SpinWaitBackoffNone;
typedef _SpinWait<0> _SpinWaitNoYield;
//
// This reentrant lock uses CRITICAL_SECTION and is intended for use when kernel blocking
// is desirable and where it is either known that the lock will be taken recursively in
// the same thread, or not known that a non-reentrant lock can be used safely.
//
class _ReentrantBlockingLock
{
public:
// Constructor for _ReentrantBlockingLock
_CONCRTIMP _ReentrantBlockingLock();
// Destructor for _ReentrantBlockingLock
_CONCRTIMP ~_ReentrantBlockingLock();
// Acquire the lock, spin if necessary
_CONCRTIMP void _Acquire();
// Tries to acquire the lock, does not spin.
// Returns true if the acquisition worked, false otherwise
_CONCRTIMP bool _TryAcquire();
// Releases the lock
_CONCRTIMP void _Release();
// An exception safe RAII wrapper.
class _Scoped_lock
{
public:
// Constructs a holder and acquires the specified lock
explicit _Scoped_lock(_ReentrantBlockingLock& _Lock) : _M_lock(_Lock)
{
_M_lock._Acquire();
}
// Destroys the holder and releases the lock
~_Scoped_lock()
{
_M_lock._Release();
}
private:
_ReentrantBlockingLock& _M_lock;
_Scoped_lock(const _Scoped_lock&); // no copy constructor
_Scoped_lock const & operator=(const _Scoped_lock&); // no assignment operator
};
private:
// Critical section requires windows.h. Hide the implementation so that
// user code need not include windows.
_CONCRT_BUFFER _M_criticalSection[(4 * sizeof(void *) + 2 * sizeof(long) + sizeof(_CONCRT_BUFFER) - 1) / sizeof(_CONCRT_BUFFER)]{};
};
//
// This reentrant lock is a pure spin lock and is intended for use when kernel blocking
// is desirable and where it is either known that the lock will be taken recursively in
// the same thread, or not known that a non-reentrant lock can be used safely.
//
class _ReentrantLock
{
public:
// Constructor for _ReentrantLock
_CONCRTIMP _ReentrantLock();
// Acquire the lock, spin if necessary
_CONCRTIMP void _Acquire();
// Tries to acquire the lock, does not spin
// Returns true if the acquisition worked, false otherwise
_CONCRTIMP bool _TryAcquire();
// Releases the lock
_CONCRTIMP void _Release();
// An exception safe RAII wrapper.
class _Scoped_lock
{
public:
// Constructs a holder and acquires the specified lock
explicit _Scoped_lock(_ReentrantLock& _Lock) : _M_lock(_Lock)
{
_M_lock._Acquire();
}
// Destroys the holder and releases the lock
~_Scoped_lock()
{
_M_lock._Release();
}
private:
_ReentrantLock& _M_lock;
_Scoped_lock(const _Scoped_lock&); // no copy constructor
_Scoped_lock const & operator=(const _Scoped_lock&); // no assignment operator
};
private:
long _M_recursionCount;
volatile long _M_owner;
};
//
// This non-reentrant lock uses CRITICAL_SECTION and is intended for use in situations
// where it is known that the lock will not be taken recursively, and can be more
// efficiently implemented.
//
class _NonReentrantBlockingLock
{
public:
// Constructor for _NonReentrantBlockingLock
//
// The constructor is exported because _NonReentrantLock is
// included in DevUnitTests.
_CONCRTIMP _NonReentrantBlockingLock();
// Constructor for _NonReentrantBlockingLock
_CONCRTIMP ~_NonReentrantBlockingLock();
// Acquire the lock, spin if necessary
_CONCRTIMP void _Acquire();
// Tries to acquire the lock, does not spin
// Returns true if the lock is taken, false otherwise
_CONCRTIMP bool _TryAcquire();
// Releases the lock
_CONCRTIMP void _Release();
// An exception safe RAII wrapper.
class _Scoped_lock
{
public:
// Constructs a holder and acquires the specified lock
explicit _Scoped_lock(_NonReentrantBlockingLock& _Lock) : _M_lock(_Lock)
{
_M_lock._Acquire();
}
// Destroys the holder and releases the lock
~_Scoped_lock()
{
_M_lock._Release();
}
private:
_NonReentrantBlockingLock& _M_lock;
_Scoped_lock(const _Scoped_lock&); // no copy constructor
_Scoped_lock const & operator=(const _Scoped_lock&); // no assignment operator
};
private:
// Critical section requires windows.h. Hide the implementation so that
// user code need not include windows.h
_CONCRT_BUFFER _M_criticalSection[(4 * sizeof(void *) + 2 * sizeof(long) + sizeof(_CONCRT_BUFFER) - 1) / sizeof(_CONCRT_BUFFER)]{};
};
//
// A Reader-Writer Lock is intended for use in situations with many readers and rare
// writers.
//
// A writer request immediately blocks future readers and then waits until all current
// readers drain. A reader request does not block future writers and must wait until
// all writers are done, even those that cut in front of it. In any race between a
// reader and a writer, the writer always wins.
//
class _ReaderWriterLock
{
public:
// Constructor for _ReaderWriterLock
//
// The constructor and destructor are exported because _ReaderWriterLock is
// included in DevUnitTests.
_CONCRTIMP _ReaderWriterLock();
// Acquire lock for reading. Spins until all writers finish, new writers
// can cut in front of a waiting reader.
_CONCRTIMP void _AcquireRead();
// Release lock for reading. The last reader changes m_state to State.kFree
_CONCRTIMP void _ReleaseRead();
// Acquire lock for writing. Spin until no readers exist, then acquire lock
// and prevent new readers.
_CONCRTIMP void _AcquireWrite();
// Release lock for writing.
_CONCRTIMP void _ReleaseWrite();
// Try to acquire the write lock, do not spin if unable to acquire.
// Returns true if the acquisition worked, false otherwise
_CONCRTIMP bool _TryAcquireWrite();
// Returns true if it is in write state, false otherwise
bool _HasWriteLock() const
{
return (_M_state == _Write);
}
// Guarantees that all writers are out of the lock. This does nothing if there are no pending writers.
void _FlushWriteOwners();
// An exception safe RAII wrapper.
class _Scoped_lock
{
public:
// Constructs a holder and acquires the writer lock
explicit _Scoped_lock(_ReaderWriterLock& _Lock) : _M_lock(_Lock)
{
_M_lock._AcquireWrite();
}
// Destroys the holder and releases the writer lock
~_Scoped_lock()
{
_M_lock._ReleaseWrite();
}
private:
_ReaderWriterLock& _M_lock;
_Scoped_lock(const _Scoped_lock&); // no copy constructor
_Scoped_lock const & operator=(const _Scoped_lock&); // no assignment operator
};
// An exception safe RAII wrapper for reads.
class _Scoped_lock_read
{
public:
// Constructs a holder and acquires the reader lock
explicit _Scoped_lock_read(_ReaderWriterLock& _Lock) : _M_lock(_Lock)
{
_M_lock._AcquireRead();
}