This repository has been archived by the owner on Oct 12, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 424
/
osthread.d
2724 lines (2412 loc) · 83.9 KB
/
osthread.d
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
/**
* The osthread module provides low-level, OS-dependent code
* for thread creation and management.
*
* Copyright: Copyright Sean Kelly 2005 - 2012.
* License: Distributed under the
* $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0).
* (See accompanying file LICENSE)
* Authors: Sean Kelly, Walter Bright, Alex Rønne Petersen, Martin Nowak
* Source: $(DRUNTIMESRC core/thread/osthread.d)
*/
module core.thread.osthread;
import core.thread.threadbase;
import core.thread.context;
import core.thread.types;
import core.atomic;
import core.memory : GC;
import core.time;
import core.exception : onOutOfMemoryError;
import core.internal.traits : externDFunc;
///////////////////////////////////////////////////////////////////////////////
// Platform Detection and Memory Allocation
///////////////////////////////////////////////////////////////////////////////
version (OSX)
version = Darwin;
else version (iOS)
version = Darwin;
else version (TVOS)
version = Darwin;
else version (WatchOS)
version = Darwin;
version (D_InlineAsm_X86)
{
version (Windows)
version = AsmX86_Windows;
else version (Posix)
version = AsmX86_Posix;
}
else version (D_InlineAsm_X86_64)
{
version (Windows)
{
version = AsmX86_64_Windows;
}
else version (Posix)
{
version = AsmX86_64_Posix;
}
}
version (Posix)
{
version (AsmX86_Windows) {} else
version (AsmX86_Posix) {} else
version (AsmX86_64_Windows) {} else
version (AsmX86_64_Posix) {} else
version (AsmExternal) {} else
{
// NOTE: The ucontext implementation requires architecture specific
// data definitions to operate so testing for it must be done
// by checking for the existence of ucontext_t rather than by
// a version identifier. Please note that this is considered
// an obsolescent feature according to the POSIX spec, so a
// custom solution is still preferred.
import core.sys.posix.ucontext;
}
}
version (Windows)
{
import core.stdc.stdint : uintptr_t; // for _beginthreadex decl below
import core.stdc.stdlib; // for malloc, atexit
import core.sys.windows.basetsd /+: HANDLE+/;
import core.sys.windows.threadaux /+: getThreadStackBottom, impersonate_thread, OpenThreadHandle+/;
import core.sys.windows.winbase /+: CloseHandle, CREATE_SUSPENDED, DuplicateHandle, GetCurrentThread,
GetCurrentThreadId, GetCurrentProcess, GetExitCodeThread, GetSystemInfo, GetThreadContext,
GetThreadPriority, INFINITE, ResumeThread, SetThreadPriority, Sleep, STILL_ACTIVE,
SuspendThread, SwitchToThread, SYSTEM_INFO, THREAD_PRIORITY_IDLE, THREAD_PRIORITY_NORMAL,
THREAD_PRIORITY_TIME_CRITICAL, WAIT_OBJECT_0, WaitForSingleObject+/;
import core.sys.windows.windef /+: TRUE+/;
import core.sys.windows.winnt /+: CONTEXT, CONTEXT_CONTROL, CONTEXT_INTEGER+/;
private extern (Windows) alias btex_fptr = uint function(void*);
private extern (C) uintptr_t _beginthreadex(void*, uint, btex_fptr, void*, uint, uint*) nothrow @nogc;
}
else version (Posix)
{
import core.stdc.errno;
import core.sys.posix.semaphore;
import core.sys.posix.stdlib; // for malloc, valloc, free, atexit
import core.sys.posix.pthread;
import core.sys.posix.signal;
import core.sys.posix.time;
version (Darwin)
{
import core.sys.darwin.mach.thread_act;
import core.sys.darwin.pthread : pthread_mach_thread_np;
}
}
version (Solaris)
{
import core.sys.solaris.sys.priocntl;
import core.sys.solaris.sys.types;
import core.sys.posix.sys.wait : idtype_t;
}
version (GNU)
{
import gcc.builtins;
}
/**
* Hook for whatever EH implementation is used to save/restore some data
* per stack.
*
* Params:
* newContext = The return value of the prior call to this function
* where the stack was last swapped out, or null when a fiber stack
* is switched in for the first time.
*/
private extern(C) void* _d_eh_swapContext(void* newContext) nothrow @nogc;
version (DigitalMars)
{
version (Windows)
{
extern(D) void* swapContext(void* newContext) nothrow @nogc
{
return _d_eh_swapContext(newContext);
}
}
else
{
extern(C) void* _d_eh_swapContextDwarf(void* newContext) nothrow @nogc;
extern(D) void* swapContext(void* newContext) nothrow @nogc
{
/* Detect at runtime which scheme is being used.
* Eventually, determine it statically.
*/
static int which = 0;
final switch (which)
{
case 0:
{
assert(newContext == null);
auto p = _d_eh_swapContext(newContext);
auto pdwarf = _d_eh_swapContextDwarf(newContext);
if (p)
{
which = 1;
return p;
}
else if (pdwarf)
{
which = 2;
return pdwarf;
}
return null;
}
case 1:
return _d_eh_swapContext(newContext);
case 2:
return _d_eh_swapContextDwarf(newContext);
}
}
}
}
else
{
extern(D) void* swapContext(void* newContext) nothrow @nogc
{
return _d_eh_swapContext(newContext);
}
}
///////////////////////////////////////////////////////////////////////////////
// Thread
///////////////////////////////////////////////////////////////////////////////
/**
* This class encapsulates all threading functionality for the D
* programming language. As thread manipulation is a required facility
* for garbage collection, all user threads should derive from this
* class, and instances of this class should never be explicitly deleted.
* A new thread may be created using either derivation or composition, as
* in the following example.
*/
class Thread : ThreadBase
{
//
// Main process thread
//
version (FreeBSD)
{
// set when suspend failed and should be retried, see Issue 13416
private shared bool m_suspendagain;
}
//
// Standard thread data
//
version (Windows)
{
private HANDLE m_hndl;
}
version (Posix)
{
private shared bool m_isRunning;
}
version (Darwin)
{
private mach_port_t m_tmach;
}
version (Solaris)
{
private __gshared bool m_isRTClass;
}
//
// Standard types
//
version (Windows)
{
alias TLSKey = uint;
}
else version (Posix)
{
alias TLSKey = pthread_key_t;
}
///////////////////////////////////////////////////////////////////////////
// Initialization
///////////////////////////////////////////////////////////////////////////
/**
* Initializes a thread object which is associated with a static
* D function.
*
* Params:
* fn = The thread function.
* sz = The stack size for this thread.
*
* In:
* fn must not be null.
*/
this( void function() fn, size_t sz = 0 ) @safe pure nothrow @nogc
{
super(fn, sz);
}
/**
* Initializes a thread object which is associated with a dynamic
* D function.
*
* Params:
* dg = The thread function.
* sz = The stack size for this thread.
*
* In:
* dg must not be null.
*/
this( void delegate() dg, size_t sz = 0 ) @safe pure nothrow @nogc
{
super(dg, sz);
}
package this( size_t sz = 0 ) @safe pure nothrow @nogc
{
super(sz);
}
/**
* Cleans up any remaining resources used by this object.
*/
~this() nothrow @nogc
{
if (super.destructBeforeDtor())
return;
version (Windows)
{
m_addr = m_addr.init;
CloseHandle( m_hndl );
m_hndl = m_hndl.init;
}
else version (Posix)
{
if (m_addr != m_addr.init)
pthread_detach( m_addr );
m_addr = m_addr.init;
}
version (Darwin)
{
m_tmach = m_tmach.init;
}
}
//
// Thread entry point. Invokes the function or delegate passed on
// construction (if any).
//
private final void run()
{
super.run();
}
/**
* Provides a reference to the calling thread.
*
* Returns:
* The thread object representing the calling thread. The result of
* deleting this object is undefined. If the current thread is not
* attached to the runtime, a null reference is returned.
*/
static Thread getThis() @safe nothrow @nogc
{
return ThreadBase.getThis().toThread;
}
///////////////////////////////////////////////////////////////////////////
// Thread Context and GC Scanning Support
///////////////////////////////////////////////////////////////////////////
version (Windows)
{
version (X86)
{
uint[8] m_reg; // edi,esi,ebp,esp,ebx,edx,ecx,eax
}
else version (X86_64)
{
ulong[16] m_reg; // rdi,rsi,rbp,rsp,rbx,rdx,rcx,rax
// r8,r9,r10,r11,r12,r13,r14,r15
}
else
{
static assert(false, "Architecture not supported." );
}
}
else version (Darwin)
{
version (X86)
{
uint[8] m_reg; // edi,esi,ebp,esp,ebx,edx,ecx,eax
}
else version (X86_64)
{
ulong[16] m_reg; // rdi,rsi,rbp,rsp,rbx,rdx,rcx,rax
// r8,r9,r10,r11,r12,r13,r14,r15
}
else version (AArch64)
{
ulong[33] m_reg; // x0-x31, pc
}
else version (ARM)
{
uint[16] m_reg; // r0-r15
}
else version (PPC)
{
// Make the assumption that we only care about non-fp and non-vr regs.
// ??? : it seems plausible that a valid address can be copied into a VR.
uint[32] m_reg; // r0-31
}
else version (PPC64)
{
// As above.
ulong[32] m_reg; // r0-31
}
else
{
static assert(false, "Architecture not supported." );
}
}
///////////////////////////////////////////////////////////////////////////
// General Actions
///////////////////////////////////////////////////////////////////////////
/**
* Starts the thread and invokes the function or delegate passed upon
* construction.
*
* In:
* This routine may only be called once per thread instance.
*
* Throws:
* ThreadException if the thread fails to start.
*/
final Thread start() nothrow
in
{
assert( !next && !prev );
}
do
{
auto wasThreaded = multiThreadedFlag;
multiThreadedFlag = true;
scope( failure )
{
if ( !wasThreaded )
multiThreadedFlag = false;
}
version (Windows) {} else
version (Posix)
{
size_t stksz = adjustStackSize( m_sz );
pthread_attr_t attr;
if ( pthread_attr_init( &attr ) )
onThreadError( "Error initializing thread attributes" );
if ( stksz && pthread_attr_setstacksize( &attr, stksz ) )
onThreadError( "Error initializing thread stack size" );
}
version (Windows)
{
// NOTE: If a thread is just executing DllMain()
// while another thread is started here, it holds an OS internal
// lock that serializes DllMain with CreateThread. As the code
// might request a synchronization on slock (e.g. in thread_findByAddr()),
// we cannot hold that lock while creating the thread without
// creating a deadlock
//
// Solution: Create the thread in suspended state and then
// add and resume it with slock acquired
assert(m_sz <= uint.max, "m_sz must be less than or equal to uint.max");
m_hndl = cast(HANDLE) _beginthreadex( null, cast(uint) m_sz, &thread_entryPoint, cast(void*) this, CREATE_SUSPENDED, &m_addr );
if ( cast(size_t) m_hndl == 0 )
onThreadError( "Error creating thread" );
}
slock.lock_nothrow();
scope(exit) slock.unlock_nothrow();
{
++nAboutToStart;
pAboutToStart = cast(ThreadBase*)realloc(pAboutToStart, Thread.sizeof * nAboutToStart);
pAboutToStart[nAboutToStart - 1] = this;
version (Windows)
{
if ( ResumeThread( m_hndl ) == -1 )
onThreadError( "Error resuming thread" );
}
else version (Posix)
{
// NOTE: This is also set to true by thread_entryPoint, but set it
// here as well so the calling thread will see the isRunning
// state immediately.
atomicStore!(MemoryOrder.raw)(m_isRunning, true);
scope( failure ) atomicStore!(MemoryOrder.raw)(m_isRunning, false);
version (Shared)
{
auto libs = externDFunc!("rt.sections_elf_shared.pinLoadedLibraries",
void* function() @nogc nothrow)();
auto ps = cast(void**).malloc(2 * size_t.sizeof);
if (ps is null) onOutOfMemoryError();
ps[0] = cast(void*)this;
ps[1] = cast(void*)libs;
if ( pthread_create( &m_addr, &attr, &thread_entryPoint, ps ) != 0 )
{
externDFunc!("rt.sections_elf_shared.unpinLoadedLibraries",
void function(void*) @nogc nothrow)(libs);
.free(ps);
onThreadError( "Error creating thread" );
}
}
else
{
if ( pthread_create( &m_addr, &attr, &thread_entryPoint, cast(void*) this ) != 0 )
onThreadError( "Error creating thread" );
}
if ( pthread_attr_destroy( &attr ) != 0 )
onThreadError( "Error destroying thread attributes" );
}
version (Darwin)
{
m_tmach = pthread_mach_thread_np( m_addr );
if ( m_tmach == m_tmach.init )
onThreadError( "Error creating thread" );
}
return this;
}
}
/**
* Waits for this thread to complete. If the thread terminated as the
* result of an unhandled exception, this exception will be rethrown.
*
* Params:
* rethrow = Rethrow any unhandled exception which may have caused this
* thread to terminate.
*
* Throws:
* ThreadException if the operation fails.
* Any exception not handled by the joined thread.
*
* Returns:
* Any exception not handled by this thread if rethrow = false, null
* otherwise.
*/
override final Throwable join( bool rethrow = true )
{
version (Windows)
{
if ( m_addr != m_addr.init && WaitForSingleObject( m_hndl, INFINITE ) != WAIT_OBJECT_0 )
throw new ThreadException( "Unable to join thread" );
// NOTE: m_addr must be cleared before m_hndl is closed to avoid
// a race condition with isRunning. The operation is done
// with atomicStore to prevent compiler reordering.
atomicStore!(MemoryOrder.raw)(*cast(shared)&m_addr, m_addr.init);
CloseHandle( m_hndl );
m_hndl = m_hndl.init;
}
else version (Posix)
{
if ( m_addr != m_addr.init && pthread_join( m_addr, null ) != 0 )
throw new ThreadException( "Unable to join thread" );
// NOTE: pthread_join acts as a substitute for pthread_detach,
// which is normally called by the dtor. Setting m_addr
// to zero ensures that pthread_detach will not be called
// on object destruction.
m_addr = m_addr.init;
}
if ( m_unhandled )
{
if ( rethrow )
throw m_unhandled;
return m_unhandled;
}
return null;
}
///////////////////////////////////////////////////////////////////////////
// Thread Priority Actions
///////////////////////////////////////////////////////////////////////////
version (Windows)
{
@property static int PRIORITY_MIN() @nogc nothrow pure @safe
{
return THREAD_PRIORITY_IDLE;
}
@property static const(int) PRIORITY_MAX() @nogc nothrow pure @safe
{
return THREAD_PRIORITY_TIME_CRITICAL;
}
@property static int PRIORITY_DEFAULT() @nogc nothrow pure @safe
{
return THREAD_PRIORITY_NORMAL;
}
}
else
{
private struct Priority
{
int PRIORITY_MIN = int.min;
int PRIORITY_DEFAULT = int.min;
int PRIORITY_MAX = int.min;
}
/*
Lazily loads one of the members stored in a hidden global variable of
type `Priority`. Upon the first access of either member, the entire
`Priority` structure is initialized. Multiple initializations from
different threads calling this function are tolerated.
`which` must be one of `PRIORITY_MIN`, `PRIORITY_DEFAULT`,
`PRIORITY_MAX`.
*/
private static shared Priority cache;
private static int loadGlobal(string which)()
{
auto local = atomicLoad(mixin("cache." ~ which));
if (local != local.min) return local;
// There will be benign races
cache = loadPriorities;
return atomicLoad(mixin("cache." ~ which));
}
/*
Loads all priorities and returns them as a `Priority` structure. This
function is thread-neutral.
*/
private static Priority loadPriorities() @nogc nothrow @trusted
{
Priority result;
version (Solaris)
{
pcparms_t pcParms;
pcinfo_t pcInfo;
pcParms.pc_cid = PC_CLNULL;
if (priocntl(idtype_t.P_PID, P_MYID, PC_GETPARMS, &pcParms) == -1)
assert( 0, "Unable to get scheduling class" );
pcInfo.pc_cid = pcParms.pc_cid;
// PC_GETCLINFO ignores the first two args, use dummy values
if (priocntl(idtype_t.P_PID, 0, PC_GETCLINFO, &pcInfo) == -1)
assert( 0, "Unable to get scheduling class info" );
pri_t* clparms = cast(pri_t*)&pcParms.pc_clparms;
pri_t* clinfo = cast(pri_t*)&pcInfo.pc_clinfo;
result.PRIORITY_MAX = clparms[0];
if (pcInfo.pc_clname == "RT")
{
m_isRTClass = true;
// For RT class, just assume it can't be changed
result.PRIORITY_MIN = clparms[0];
result.PRIORITY_DEFAULT = clparms[0];
}
else
{
m_isRTClass = false;
// For all other scheduling classes, there are
// two key values -- uprilim and maxupri.
// maxupri is the maximum possible priority defined
// for the scheduling class, and valid priorities
// range are in [-maxupri, maxupri].
//
// However, uprilim is an upper limit that the
// current thread can set for the current scheduling
// class, which can be less than maxupri. As such,
// use this value for priorityMax since this is
// the effective maximum.
// maxupri
result.PRIORITY_MIN = -clinfo[0];
// by definition
result.PRIORITY_DEFAULT = 0;
}
}
else version (Posix)
{
int policy;
sched_param param;
pthread_getschedparam( pthread_self(), &policy, ¶m ) == 0
|| assert(0, "Internal error in pthread_getschedparam");
result.PRIORITY_MIN = sched_get_priority_min( policy );
result.PRIORITY_MIN != -1
|| assert(0, "Internal error in sched_get_priority_min");
result.PRIORITY_DEFAULT = param.sched_priority;
result.PRIORITY_MAX = sched_get_priority_max( policy );
result.PRIORITY_MAX != -1 ||
assert(0, "Internal error in sched_get_priority_max");
}
else
{
static assert(0, "Your code here.");
}
return result;
}
/**
* The minimum scheduling priority that may be set for a thread. On
* systems where multiple scheduling policies are defined, this value
* represents the minimum valid priority for the scheduling policy of
* the process.
*/
@property static int PRIORITY_MIN() @nogc nothrow pure @trusted
{
return (cast(int function() @nogc nothrow pure @safe)
&loadGlobal!"PRIORITY_MIN")();
}
/**
* The maximum scheduling priority that may be set for a thread. On
* systems where multiple scheduling policies are defined, this value
* represents the maximum valid priority for the scheduling policy of
* the process.
*/
@property static const(int) PRIORITY_MAX() @nogc nothrow pure @trusted
{
return (cast(int function() @nogc nothrow pure @safe)
&loadGlobal!"PRIORITY_MAX")();
}
/**
* The default scheduling priority that is set for a thread. On
* systems where multiple scheduling policies are defined, this value
* represents the default priority for the scheduling policy of
* the process.
*/
@property static int PRIORITY_DEFAULT() @nogc nothrow pure @trusted
{
return (cast(int function() @nogc nothrow pure @safe)
&loadGlobal!"PRIORITY_DEFAULT")();
}
}
version (NetBSD)
{
//NetBSD does not support priority for default policy
// and it is not possible change policy without root access
int fakePriority = int.max;
}
/**
* Gets the scheduling priority for the associated thread.
*
* Note: Getting the priority of a thread that already terminated
* might return the default priority.
*
* Returns:
* The scheduling priority of this thread.
*/
final @property int priority()
{
version (Windows)
{
return GetThreadPriority( m_hndl );
}
else version (NetBSD)
{
return fakePriority==int.max? PRIORITY_DEFAULT : fakePriority;
}
else version (Posix)
{
int policy;
sched_param param;
if (auto err = pthread_getschedparam(m_addr, &policy, ¶m))
{
// ignore error if thread is not running => Bugzilla 8960
if (!atomicLoad(m_isRunning)) return PRIORITY_DEFAULT;
throw new ThreadException("Unable to get thread priority");
}
return param.sched_priority;
}
}
/**
* Sets the scheduling priority for the associated thread.
*
* Note: Setting the priority of a thread that already terminated
* might have no effect.
*
* Params:
* val = The new scheduling priority of this thread.
*/
final @property void priority( int val )
in
{
assert(val >= PRIORITY_MIN);
assert(val <= PRIORITY_MAX);
}
do
{
version (Windows)
{
if ( !SetThreadPriority( m_hndl, val ) )
throw new ThreadException( "Unable to set thread priority" );
}
else version (Solaris)
{
// the pthread_setschedprio(3c) and pthread_setschedparam functions
// are broken for the default (TS / time sharing) scheduling class.
// instead, we use priocntl(2) which gives us the desired behavior.
// We hardcode the min and max priorities to the current value
// so this is a no-op for RT threads.
if (m_isRTClass)
return;
pcparms_t pcparm;
pcparm.pc_cid = PC_CLNULL;
if (priocntl(idtype_t.P_LWPID, P_MYID, PC_GETPARMS, &pcparm) == -1)
throw new ThreadException( "Unable to get scheduling class" );
pri_t* clparms = cast(pri_t*)&pcparm.pc_clparms;
// clparms is filled in by the PC_GETPARMS call, only necessary
// to adjust the element that contains the thread priority
clparms[1] = cast(pri_t) val;
if (priocntl(idtype_t.P_LWPID, P_MYID, PC_SETPARMS, &pcparm) == -1)
throw new ThreadException( "Unable to set scheduling class" );
}
else version (NetBSD)
{
fakePriority = val;
}
else version (Posix)
{
static if (__traits(compiles, pthread_setschedprio))
{
if (auto err = pthread_setschedprio(m_addr, val))
{
// ignore error if thread is not running => Bugzilla 8960
if (!atomicLoad(m_isRunning)) return;
throw new ThreadException("Unable to set thread priority");
}
}
else
{
// NOTE: pthread_setschedprio is not implemented on Darwin, FreeBSD, OpenBSD,
// or DragonFlyBSD, so use the more complicated get/set sequence below.
int policy;
sched_param param;
if (auto err = pthread_getschedparam(m_addr, &policy, ¶m))
{
// ignore error if thread is not running => Bugzilla 8960
if (!atomicLoad(m_isRunning)) return;
throw new ThreadException("Unable to set thread priority");
}
param.sched_priority = val;
if (auto err = pthread_setschedparam(m_addr, policy, ¶m))
{
// ignore error if thread is not running => Bugzilla 8960
if (!atomicLoad(m_isRunning)) return;
throw new ThreadException("Unable to set thread priority");
}
}
}
}
unittest
{
auto thr = Thread.getThis();
immutable prio = thr.priority;
scope (exit) thr.priority = prio;
assert(prio == PRIORITY_DEFAULT);
assert(prio >= PRIORITY_MIN && prio <= PRIORITY_MAX);
thr.priority = PRIORITY_MIN;
assert(thr.priority == PRIORITY_MIN);
thr.priority = PRIORITY_MAX;
assert(thr.priority == PRIORITY_MAX);
}
unittest // Bugzilla 8960
{
import core.sync.semaphore;
auto thr = new Thread({});
thr.start();
Thread.sleep(1.msecs); // wait a little so the thread likely has finished
thr.priority = PRIORITY_MAX; // setting priority doesn't cause error
auto prio = thr.priority; // getting priority doesn't cause error
assert(prio >= PRIORITY_MIN && prio <= PRIORITY_MAX);
}
/**
* Tests whether this thread is running.
*
* Returns:
* true if the thread is running, false if not.
*/
override final @property bool isRunning() nothrow @nogc
{
if (!super.isRunning())
return false;
version (Windows)
{
uint ecode = 0;
GetExitCodeThread( m_hndl, &ecode );
return ecode == STILL_ACTIVE;
}
else version (Posix)
{
return atomicLoad(m_isRunning);
}
}
///////////////////////////////////////////////////////////////////////////
// Actions on Calling Thread
///////////////////////////////////////////////////////////////////////////
/**
* Suspends the calling thread for at least the supplied period. This may
* result in multiple OS calls if period is greater than the maximum sleep
* duration supported by the operating system.
*
* Params:
* val = The minimum duration the calling thread should be suspended.
*
* In:
* period must be non-negative.
*
* Example:
* ------------------------------------------------------------------------
*
* Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
* Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
*
* ------------------------------------------------------------------------
*/
static void sleep( Duration val ) @nogc nothrow
in
{
assert( !val.isNegative );
}
do
{
version (Windows)
{
auto maxSleepMillis = dur!("msecs")( uint.max - 1 );
// avoid a non-zero time to be round down to 0
if ( val > dur!"msecs"( 0 ) && val < dur!"msecs"( 1 ) )
val = dur!"msecs"( 1 );
// NOTE: In instances where all other threads in the process have a
// lower priority than the current thread, the current thread
// will not yield with a sleep time of zero. However, unlike
// yield(), the user is not asking for a yield to occur but
// only for execution to suspend for the requested interval.
// Therefore, expected performance may not be met if a yield
// is forced upon the user.
while ( val > maxSleepMillis )
{
Sleep( cast(uint)
maxSleepMillis.total!"msecs" );
val -= maxSleepMillis;
}
Sleep( cast(uint) val.total!"msecs" );
}
else version (Posix)
{
timespec tin = void;
timespec tout = void;
val.split!("seconds", "nsecs")(tin.tv_sec, tin.tv_nsec);
if ( val.total!"seconds" > tin.tv_sec.max )
tin.tv_sec = tin.tv_sec.max;
while ( true )
{
if ( !nanosleep( &tin, &tout ) )
return;
if ( errno != EINTR )
assert(0, "Unable to sleep for the specified duration");
tin = tout;
}
}
}
/**
* Forces a context switch to occur away from the calling thread.
*/
static void yield() @nogc nothrow
{
version (Windows)
SwitchToThread();
else version (Posix)
sched_yield();
}
}
private Thread toThread(return scope ThreadBase t) @trusted nothrow @nogc pure
{
return cast(Thread) cast(void*) t;
}
private extern(D) static void thread_yield() @nogc nothrow
{
Thread.yield();
}
///
unittest
{
class DerivedThread : Thread
{