This repository has been archived by the owner on Oct 12, 2022. It is now read-only.
/
thread.d
5131 lines (4519 loc) · 151 KB
/
thread.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 thread module provides support 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.d)
*/
module core.thread;
public import core.time; // for Duration
import core.exception : onOutOfMemoryError;
private
{
// interface to rt.tlsgc
import core.internal.traits : externDFunc;
alias rt_tlsgc_init = externDFunc!("rt.tlsgc.init", void* function());
alias rt_tlsgc_destroy = externDFunc!("rt.tlsgc.destroy", void function(void*));
alias ScanDg = void delegate(void* pstart, void* pend) nothrow;
alias rt_tlsgc_scan =
externDFunc!("rt.tlsgc.scan", void function(void*, scope ScanDg) nothrow);
alias rt_tlsgc_processGCMarks =
externDFunc!("rt.tlsgc.processGCMarks", void function(void*, scope IsMarkedDg) nothrow);
}
version( Solaris )
{
import core.sys.solaris.sys.priocntl;
import core.sys.solaris.sys.types;
}
// this should be true for most architectures
version = StackGrowsDown;
/**
* Returns the process ID of the calling process, which is guaranteed to be
* unique on the system. This call is always successful.
*
* Example:
* ---
* writefln("Current process id: %s", getpid());
* ---
*/
version(Posix)
{
alias core.sys.posix.unistd.getpid getpid;
}
else version (Windows)
{
alias core.sys.windows.windows.GetCurrentProcessId getpid;
}
///////////////////////////////////////////////////////////////////////////////
// Thread and Fiber Exceptions
///////////////////////////////////////////////////////////////////////////////
/**
* Base class for thread exceptions.
*/
class ThreadException : Exception
{
@safe pure nothrow this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null)
{
super(msg, file, line, next);
}
@safe pure nothrow this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__)
{
super(msg, file, line, next);
}
}
/**
* Base class for thread errors to be used for function inside GC when allocations are unavailable.
*/
class ThreadError : Error
{
@safe pure nothrow this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null)
{
super(msg, file, line, next);
}
@safe pure nothrow this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__)
{
super(msg, file, line, next);
}
}
/**
* Base class for fiber exceptions.
*/
class FiberException : Exception
{
@safe pure nothrow this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null)
{
super(msg, file, line, next);
}
@safe pure nothrow this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__)
{
super(msg, file, line, next);
}
}
private
{
import core.sync.mutex;
import core.atomic;
//
// from core.memory
//
extern (C) void gc_enable();
extern (C) void gc_disable();
extern (C) void* gc_malloc(size_t sz, uint ba = 0);
//
// from core.stdc.string
//
extern (C) void* memcpy(void*, const void*, size_t);
//
// exposed by compiler runtime
//
extern (C) void rt_moduleTlsCtor();
extern (C) void rt_moduleTlsDtor();
alias void delegate() gc_atom;
extern (C) void function(scope gc_atom) gc_atomic;
}
///////////////////////////////////////////////////////////////////////////////
// Thread Entry Point and Signal Handlers
///////////////////////////////////////////////////////////////////////////////
version( Windows )
{
private
{
import core.stdc.stdint : uintptr_t; // for _beginthreadex decl below
import core.stdc.stdlib; // for malloc, atexit
import core.sys.windows.windows;
import core.sys.windows.threadaux; // for OpenThreadHandle
const DWORD TLS_OUT_OF_INDEXES = 0xFFFFFFFF;
const CREATE_SUSPENDED = 0x00000004;
extern (Windows) alias uint function(void*) btex_fptr;
extern (C) uintptr_t _beginthreadex(void*, uint, btex_fptr, void*, uint, uint*);
//
// Entry point for Windows threads
//
extern (Windows) uint thread_entryPoint( void* arg )
{
Thread obj = cast(Thread) arg;
assert( obj );
assert( obj.m_curr is &obj.m_main );
obj.m_main.bstack = getStackBottom();
obj.m_main.tstack = obj.m_main.bstack;
obj.m_tlsgcdata = rt_tlsgc_init();
Thread.setThis( obj );
//Thread.add( obj );
scope( exit )
{
Thread.remove( obj );
}
Thread.add( &obj.m_main );
// NOTE: No GC allocations may occur until the stack pointers have
// been set and Thread.getThis returns a valid reference to
// this thread object (this latter condition is not strictly
// necessary on Windows but it should be followed for the
// sake of consistency).
// TODO: Consider putting an auto exception object here (using
// alloca) forOutOfMemoryError plus something to track
// whether an exception is in-flight?
void append( Throwable t )
{
if( obj.m_unhandled is null )
obj.m_unhandled = t;
else
{
Throwable last = obj.m_unhandled;
while( last.next !is null )
last = last.next;
last.next = t;
}
}
version( D_InlineAsm_X86 )
{
asm nothrow @nogc { fninit; }
}
try
{
rt_moduleTlsCtor();
try
{
obj.run();
}
catch( Throwable t )
{
append( t );
}
rt_moduleTlsDtor();
}
catch( Throwable t )
{
append( t );
}
return 0;
}
HANDLE GetCurrentThreadHandle()
{
const uint DUPLICATE_SAME_ACCESS = 0x00000002;
HANDLE curr = GetCurrentThread(),
proc = GetCurrentProcess(),
hndl;
DuplicateHandle( proc, curr, proc, &hndl, 0, TRUE, DUPLICATE_SAME_ACCESS );
return hndl;
}
}
}
else version( Posix )
{
private
{
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( OSX )
{
import core.sys.osx.mach.thread_act;
extern (C) mach_port_t pthread_mach_thread_np(pthread_t);
}
version( GNU )
{
import gcc.builtins;
}
//
// Entry point for POSIX threads
//
extern (C) void* thread_entryPoint( void* arg )
{
version (Shared)
{
import rt.sections;
Thread obj = cast(Thread)(cast(void**)arg)[0];
auto loadedLibraries = (cast(void**)arg)[1];
.free(arg);
}
else
{
Thread obj = cast(Thread)arg;
}
assert( obj );
assert( obj.m_curr is &obj.m_main );
obj.m_main.bstack = getStackBottom();
obj.m_main.tstack = obj.m_main.bstack;
obj.m_tlsgcdata = rt_tlsgc_init();
atomicStore!(MemoryOrder.raw)(obj.m_isRunning, true);
Thread.setThis( obj );
//Thread.add( obj );
scope( exit )
{
// NOTE: isRunning should be set to false after the thread is
// removed or a double-removal could occur between this
// function and thread_suspendAll.
Thread.remove( obj );
atomicStore!(MemoryOrder.raw)(obj.m_isRunning,false);
}
Thread.add( &obj.m_main );
static extern (C) void thread_cleanupHandler( void* arg ) nothrow
{
Thread obj = cast(Thread) arg;
assert( obj );
// NOTE: If the thread terminated abnormally, just set it as
// not running and let thread_suspendAll remove it from
// the thread list. This is safer and is consistent
// with the Windows thread code.
atomicStore!(MemoryOrder.raw)(obj.m_isRunning,false);
}
// NOTE: Using void to skip the initialization here relies on
// knowledge of how pthread_cleanup is implemented. It may
// not be appropriate for all platforms. However, it does
// avoid the need to link the pthread module. If any
// implementation actually requires default initialization
// then pthread_cleanup should be restructured to maintain
// the current lack of a link dependency.
static if( __traits( compiles, pthread_cleanup ) )
{
pthread_cleanup cleanup = void;
cleanup.push( &thread_cleanupHandler, cast(void*) obj );
}
else static if( __traits( compiles, pthread_cleanup_push ) )
{
pthread_cleanup_push( &thread_cleanupHandler, cast(void*) obj );
}
else
{
static assert( false, "Platform not supported." );
}
// NOTE: No GC allocations may occur until the stack pointers have
// been set and Thread.getThis returns a valid reference to
// this thread object (this latter condition is not strictly
// necessary on Windows but it should be followed for the
// sake of consistency).
// TODO: Consider putting an auto exception object here (using
// alloca) forOutOfMemoryError plus something to track
// whether an exception is in-flight?
void append( Throwable t )
{
if( obj.m_unhandled is null )
obj.m_unhandled = t;
else
{
Throwable last = obj.m_unhandled;
while( last.next !is null )
last = last.next;
last.next = t;
}
}
try
{
version (Shared) inheritLoadedLibraries(loadedLibraries);
rt_moduleTlsCtor();
try
{
obj.run();
}
catch( Throwable t )
{
append( t );
}
rt_moduleTlsDtor();
version (Shared) cleanupLoadedLibraries();
}
catch( Throwable t )
{
append( t );
}
// NOTE: Normal cleanup is handled by scope(exit).
static if( __traits( compiles, pthread_cleanup ) )
{
cleanup.pop( 0 );
}
else static if( __traits( compiles, pthread_cleanup_push ) )
{
pthread_cleanup_pop( 0 );
}
return null;
}
//
// Used to track the number of suspended threads
//
__gshared sem_t suspendCount;
extern (C) void thread_suspendHandler( int sig ) nothrow
in
{
assert( sig == suspendSignalNumber );
}
body
{
void op(void* sp) nothrow
{
// NOTE: Since registers are being pushed and popped from the
// stack, any other stack data used by this function should
// be gone before the stack cleanup code is called below.
Thread obj = Thread.getThis();
// NOTE: The thread reference returned by getThis is set within
// the thread startup code, so it is possible that this
// handler may be called before the reference is set. In
// this case it is safe to simply suspend and not worry
// about the stack pointers as the thread will not have
// any references to GC-managed data.
if( obj && !obj.m_lock )
{
obj.m_curr.tstack = getStackTop();
}
sigset_t sigres = void;
int status;
status = sigfillset( &sigres );
assert( status == 0 );
status = sigdelset( &sigres, resumeSignalNumber );
assert( status == 0 );
status = sem_post( &suspendCount );
assert( status == 0 );
sigsuspend( &sigres );
if( obj && !obj.m_lock )
{
obj.m_curr.tstack = obj.m_curr.bstack;
}
}
callWithStackShell(&op);
}
extern (C) void thread_resumeHandler( int sig ) nothrow
in
{
assert( sig == resumeSignalNumber );
}
body
{
}
}
}
else
{
// NOTE: This is the only place threading versions are checked. If a new
// version is added, the module code will need to be searched for
// places where version-specific code may be required. This can be
// easily accomlished by searching for 'Windows' or 'Posix'.
static assert( false, "Unknown threading implementation." );
}
///////////////////////////////////////////////////////////////////////////////
// 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
{
///////////////////////////////////////////////////////////////////////////
// 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 )
in
{
assert( fn );
}
body
{
this();
m_fn = fn;
m_sz = sz;
m_call = Call.FN;
m_curr = &m_main;
}
/**
* 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 )
in
{
assert( dg );
}
body
{
this();
m_dg = dg;
m_sz = sz;
m_call = Call.DG;
m_curr = &m_main;
}
/**
* Cleans up any remaining resources used by this object.
*/
~this()
{
if( m_addr == m_addr.init )
{
return;
}
version( Windows )
{
m_addr = m_addr.init;
CloseHandle( m_hndl );
m_hndl = m_hndl.init;
}
else version( Posix )
{
pthread_detach( m_addr );
m_addr = m_addr.init;
}
version( OSX )
{
m_tmach = m_tmach.init;
}
rt_tlsgc_destroy( m_tlsgcdata );
m_tlsgcdata = null;
}
///////////////////////////////////////////////////////////////////////////
// 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()
in
{
assert( !next && !prev );
}
body
{
auto wasThreaded = multiThreadedFlag;
multiThreadedFlag = true;
scope( failure )
{
if( !wasThreaded )
multiThreadedFlag = false;
}
version( Windows ) {} else
version( Posix )
{
pthread_attr_t attr;
if( pthread_attr_init( &attr ) )
throw new ThreadException( "Error initializing thread attributes" );
if( m_sz && pthread_attr_setstacksize( &attr, m_sz ) )
throw new ThreadException( "Error initializing thread stack size" );
if( pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ) )
throw new ThreadException( "Error setting thread joinable" );
}
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 )
throw new ThreadException( "Error creating thread" );
}
// NOTE: The starting thread must be added to the global thread list
// here rather than within thread_entryPoint to prevent a race
// with the main thread, which could finish and terminat the
// app without ever knowing that it should have waited for this
// starting thread. In effect, not doing the add here risks
// having thread being treated like a daemon thread.
synchronized( slock )
{
version( Windows )
{
if( ResumeThread( m_hndl ) == -1 )
throw new ThreadException( "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)
{
import rt.sections;
auto libs = pinLoadedLibraries();
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 )
{
unpinLoadedLibraries(libs);
.free(ps);
throw new ThreadException( "Error creating thread" );
}
}
else
{
if( pthread_create( &m_addr, &attr, &thread_entryPoint, cast(void*) this ) != 0 )
throw new ThreadException( "Error creating thread" );
}
}
version( OSX )
{
m_tmach = pthread_mach_thread_np( m_addr );
if( m_tmach == m_tmach.init )
throw new ThreadException( "Error creating thread" );
}
// NOTE: when creating threads from inside a DLL, DllMain(THREAD_ATTACH)
// might be called before ResumeThread returns, but the dll
// helper functions need to know whether the thread is created
// from the runtime itself or from another DLL or the application
// to just attach to it
// as a consequence, the new Thread object is added before actual
// creation of the thread. There should be no problem with the GC
// calling thread_suspendAll, because of the slock synchronization
//
// VERIFY: does this actually also apply to other platforms?
add( this );
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.
*/
final Throwable join( bool rethrow = true )
{
version( Windows )
{
if( 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( 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;
}
///////////////////////////////////////////////////////////////////////////
// General Properties
///////////////////////////////////////////////////////////////////////////
/**
* Gets the user-readable label for this thread.
*
* Returns:
* The name of this thread.
*/
final @property string name()
{
synchronized( this )
{
return m_name;
}
}
/**
* Sets the user-readable label for this thread.
*
* Params:
* val = The new name of this thread.
*/
final @property void name( string val )
{
synchronized( this )
{
m_name = val;
}
}
/**
* Gets the daemon status for this thread. While the runtime will wait for
* all normal threads to complete before tearing down the process, daemon
* threads are effectively ignored and thus will not prevent the process
* from terminating. In effect, daemon threads will be terminated
* automatically by the OS when the process exits.
*
* Returns:
* true if this is a daemon thread.
*/
final @property bool isDaemon()
{
synchronized( this )
{
return m_isDaemon;
}
}
/**
* Sets the daemon status for this thread. While the runtime will wait for
* all normal threads to complete before tearing down the process, daemon
* threads are effectively ignored and thus will not prevent the process
* from terminating. In effect, daemon threads will be terminated
* automatically by the OS when the process exits.
*
* Params:
* val = The new daemon status for this thread.
*/
final @property void isDaemon( bool val )
{
synchronized( this )
{
m_isDaemon = val;
}
}
/**
* Tests whether this thread is running.
*
* Returns:
* true if the thread is running, false if not.
*/
final @property bool isRunning() nothrow
{
if( m_addr == m_addr.init )
{
return false;
}
version( Windows )
{
uint ecode = 0;
GetExitCodeThread( m_hndl, &ecode );
return ecode == STILL_ACTIVE;
}
else version( Posix )
{
return atomicLoad(m_isRunning);
}
}
///////////////////////////////////////////////////////////////////////////
// Thread Priority Actions
///////////////////////////////////////////////////////////////////////////
/**
* 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.
*/
__gshared const int 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.
*/
__gshared const int 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.
*/
__gshared const int PRIORITY_DEFAULT;
/**
* 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( 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);
}
body
{
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( 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 OSX or FreeBSD, 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;