Debian Codegraph @

libphobos/libdruntime/core/thread/threadbase.d

raw
1 /**
2 * The threadbase module provides OS-independent code
3 * for thread storage and management.
4 *
5 * Copyright: Copyright Sean Kelly 2005 - 2012.
6 * License: Distributed under the
7 * $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0).
8 * (See accompanying file LICENSE)
9 * Authors: Sean Kelly, Walter Bright, Alex Rønne Petersen, Martin Nowak
10 * Source: $(DRUNTIMESRC core/thread/threadbase.d)
11 */
12
13 /* NOTE: This file has been patched from the original DMD distribution to
14 * work with the GDC compiler.
15 */
16 module core.thread.threadbase;
17
18 import core.thread.context;
19 import core.thread.types;
20 import core.time;
21 import core.sync.mutex;
22 import core.stdc.stdlib : free, realloc;
23
24 private
25 {
26 import core.internal.traits : externDFunc;
27
28 // interface to rt.tlsgc
29 alias rt_tlsgc_init = externDFunc!("rt.tlsgc.init", void* function() nothrow @nogc);
30 alias rt_tlsgc_destroy = externDFunc!("rt.tlsgc.destroy", void function(void*) nothrow @nogc);
31
32 alias ScanDg = void delegate(void* pstart, void* pend) nothrow;
33 alias rt_tlsgc_scan =
34 externDFunc!("rt.tlsgc.scan", void function(void*, scope ScanDg) nothrow);
35 }
36
37
38 ///////////////////////////////////////////////////////////////////////////////
39 // Thread and Fiber Exceptions
40 ///////////////////////////////////////////////////////////////////////////////
41
42
43 /**
44 * Base class for thread exceptions.
45 */
46 class ThreadException : Exception
47 {
48 @nogc @safe pure nothrow this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null)
49 {
50 super(msg, file, line, next);
51 }
52
53 @nogc @safe pure nothrow this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__)
54 {
55 super(msg, file, line, next);
56 }
57 }
58
59
60 /**
61 * Base class for thread errors to be used for function inside GC when allocations are unavailable.
62 */
63 class ThreadError : Error
64 {
65 @nogc @safe pure nothrow this(string msg, string file = __FILE__, size_t line = __LINE__, Throwable next = null)
66 {
67 super(msg, file, line, next);
68 }
69
70 @nogc @safe pure nothrow this(string msg, Throwable next, string file = __FILE__, size_t line = __LINE__)
71 {
72 super(msg, file, line, next);
73 }
74 }
75
76 private
77 {
78 // Handling unaligned mutexes are not supported on all platforms, so we must
79 // ensure that the address of all shared data are appropriately aligned.
80 enum mutexAlign = __traits(classInstanceAlignment, Mutex);
81 enum mutexClassInstanceSize = __traits(classInstanceSize, Mutex);
82
83 alias swapContext = externDFunc!("core.thread.osthread.swapContext", void* function(void*) nothrow @nogc);
84 }
85
86 package
87 {
88 alias getStackBottom = externDFunc!("core.thread.osthread.getStackBottom", void* function() nothrow @nogc);
89 alias getStackTop = externDFunc!("core.thread.osthread.getStackTop", void* function() nothrow @nogc);
90 }
91
92
93 ///////////////////////////////////////////////////////////////////////////////
94 // Thread
95 ///////////////////////////////////////////////////////////////////////////////
96
97
98 class ThreadBase
99 {
100 ///////////////////////////////////////////////////////////////////////////
101 // Initialization
102 ///////////////////////////////////////////////////////////////////////////
103
104 this(void function() fn, size_t sz = 0) @safe pure nothrow @nogc
105 in(fn)
106 {
107 this(sz);
108 m_call = fn;
109 }
110
111 this(void delegate() dg, size_t sz = 0) @trusted pure nothrow @nogc
112 in( cast(const void delegate()) dg)
113 {
114 this(sz);
115 m_call = dg;
116 }
117
118 /**
119 * Cleans up any remaining resources used by this object.
120 */
121 package bool destructBeforeDtor() nothrow @nogc
122 {
123 destroyDataStorageIfAvail();
124
125 bool no_context = m_addr == m_addr.init;
126 bool not_registered = !next && !prev && (sm_tbeg !is this);
127
128 return (no_context || not_registered);
129 }
130
131 ref void* tlsGCData() nothrow @nogc
132 {
133 return m_tlsgcdata;
134 }
135
136 package void tlsRTdataInit() nothrow @nogc
137 {
138 m_tlsrtdata = rt_tlsgc_init();
139 }
140
141 package void initDataStorage() nothrow
142 {
143 assert(m_curr is &m_main);
144
145 m_main.bstack = getStackBottom();
146 m_main.tstack = m_main.bstack;
147 tlsRTdataInit();
148 }
149
150 package void destroyDataStorage() nothrow @nogc
151 {
152 rt_tlsgc_destroy(m_tlsrtdata);
153 m_tlsrtdata = null;
154 }
155
156 package void destroyDataStorageIfAvail() nothrow @nogc
157 {
158 if (m_tlsrtdata)
159 destroyDataStorage();
160 }
161
162
163 ///////////////////////////////////////////////////////////////////////////
164 // General Actions
165 ///////////////////////////////////////////////////////////////////////////
166
167
168 /**
169 * Waits for this thread to complete. If the thread terminated as the
170 * result of an unhandled exception, this exception will be rethrown.
171 *
172 * Params:
173 * rethrow = Rethrow any unhandled exception which may have caused this
174 * thread to terminate.
175 *
176 * Throws:
177 * ThreadException if the operation fails.
178 * Any exception not handled by the joined thread.
179 *
180 * Returns:
181 * Any exception not handled by this thread if rethrow = false, null
182 * otherwise.
183 */
184 abstract Throwable join(bool rethrow = true);
185
186
187 ///////////////////////////////////////////////////////////////////////////
188 // General Properties
189 ///////////////////////////////////////////////////////////////////////////
190
191
192 /**
193 * Gets the OS identifier for this thread.
194 *
195 * Returns:
196 * If the thread hasn't been started yet, returns $(LREF ThreadID)$(D.init).
197 * Otherwise, returns the result of $(D GetCurrentThreadId) on Windows,
198 * and $(D pthread_self) on POSIX.
199 *
200 * The value is unique for the current process.
201 */
202 final @property ThreadID id() @safe @nogc
203 {
204 synchronized(this)
205 {
206 return m_addr;
207 }
208 }
209
210
211 /**
212 * Gets the user-readable label for this thread.
213 *
214 * Returns:
215 * The name of this thread.
216 */
217 final @property string name() @safe @nogc
218 {
219 synchronized(this)
220 {
221 return m_name;
222 }
223 }
224
225
226 /**
227 * Sets the user-readable label for this thread.
228 *
229 * Params:
230 * val = The new name of this thread.
231 */
232 final @property void name(string val) @safe @nogc
233 {
234 synchronized(this)
235 {
236 m_name = val;
237 }
238 }
239
240
241 /**
242 * Gets the daemon status for this thread. While the runtime will wait for
243 * all normal threads to complete before tearing down the process, daemon
244 * threads are effectively ignored and thus will not prevent the process
245 * from terminating. In effect, daemon threads will be terminated
246 * automatically by the OS when the process exits.
247 *
248 * Returns:
249 * true if this is a daemon thread.
250 */
251 final @property bool isDaemon() @safe @nogc
252 {
253 synchronized(this)
254 {
255 return m_isDaemon;
256 }
257 }
258
259
260 /**
261 * Sets the daemon status for this thread. While the runtime will wait for
262 * all normal threads to complete before tearing down the process, daemon
263 * threads are effectively ignored and thus will not prevent the process
264 * from terminating. In effect, daemon threads will be terminated
265 * automatically by the OS when the process exits.
266 *
267 * Params:
268 * val = The new daemon status for this thread.
269 */
270 final @property void isDaemon(bool val) @safe @nogc
271 {
272 synchronized(this)
273 {
274 m_isDaemon = val;
275 }
276 }
277
278 /**
279 * Tests whether this thread is the main thread, i.e. the thread
280 * that initialized the runtime
281 *
282 * Returns:
283 * true if the thread is the main thread
284 */
285 final @property bool isMainThread() nothrow @nogc
286 {
287 return this is sm_main;
288 }
289
290 /**
291 * Tests whether this thread is running.
292 *
293 * Returns:
294 * true if the thread is running, false if not.
295 */
296 @property bool isRunning() nothrow @nogc
297 {
298 if (m_addr == m_addr.init)
299 return false;
300
301 return true;
302 }
303
304
305 ///////////////////////////////////////////////////////////////////////////
306 // Thread Accessors
307 ///////////////////////////////////////////////////////////////////////////
308
309 /**
310 * Provides a reference to the calling thread.
311 *
312 * Returns:
313 * The thread object representing the calling thread. The result of
314 * deleting this object is undefined. If the current thread is not
315 * attached to the runtime, a null reference is returned.
316 */
317 static ThreadBase getThis() @safe nothrow @nogc
318 {
319 // NOTE: This function may not be called until thread_init has
320 // completed. See thread_suspendAll for more information
321 // on why this might occur.
322 version (GNU) pragma(inline, false);
323 return sm_this;
324 }
325
326
327 /**
328 * Provides a list of all threads currently being tracked by the system.
329 * Note that threads in the returned array might no longer run (see
330 * $(D ThreadBase.)$(LREF isRunning)).
331 *
332 * Returns:
333 * An array containing references to all threads currently being
334 * tracked by the system. The result of deleting any contained
335 * objects is undefined.
336 */
337 static ThreadBase[] getAll()
338 {
339 static void resize(ref ThreadBase[] buf, size_t nlen)
340 {
341 buf.length = nlen;
342 }
343 return getAllImpl!resize();
344 }
345
346
347 /**
348 * Operates on all threads currently being tracked by the system. The
349 * result of deleting any Thread object is undefined.
350 * Note that threads passed to the callback might no longer run (see
351 * $(D ThreadBase.)$(LREF isRunning)).
352 *
353 * Params:
354 * dg = The supplied code as a delegate.
355 *
356 * Returns:
357 * Zero if all elemented are visited, nonzero if not.
358 */
359 static int opApply(scope int delegate(ref ThreadBase) dg)
360 {
361 static void resize(ref ThreadBase[] buf, size_t nlen)
362 {
363 import core.exception: onOutOfMemoryError;
364
365 auto newBuf = cast(ThreadBase*)realloc(buf.ptr, nlen * size_t.sizeof);
366 if (newBuf is null) onOutOfMemoryError();
367 buf = newBuf[0 .. nlen];
368 }
369 auto buf = getAllImpl!resize;
370 scope(exit) if (buf.ptr) free(buf.ptr);
371
372 foreach (t; buf)
373 {
374 if (auto res = dg(t))
375 return res;
376 }
377 return 0;
378 }
379
380 private static ThreadBase[] getAllImpl(alias resize)()
381 {
382 import core.atomic;
383
384 ThreadBase[] buf;
385 while (true)
386 {
387 immutable len = atomicLoad!(MemoryOrder.raw)(*cast(shared)&sm_tlen);
388 resize(buf, len);
389 assert(buf.length == len);
390 synchronized (slock)
391 {
392 if (len == sm_tlen)
393 {
394 size_t pos;
395 for (ThreadBase t = sm_tbeg; t; t = t.next)
396 buf[pos++] = t;
397 return buf;
398 }
399 }
400 }
401 }
402
403 ///////////////////////////////////////////////////////////////////////////
404 // Actions on Calling Thread
405 ///////////////////////////////////////////////////////////////////////////
406
407 /**
408 * Forces a context switch to occur away from the calling thread.
409 */
410 private static void yield() @nogc nothrow
411 {
412 thread_yield();
413 }
414
415 ///////////////////////////////////////////////////////////////////////////
416 // Stuff That Should Go Away
417 ///////////////////////////////////////////////////////////////////////////
418
419
420 //
421 // Initializes a thread object which has no associated executable function.
422 // This is used for the main thread initialized in thread_init().
423 //
424 package this(size_t sz = 0) @safe pure nothrow @nogc
425 {
426 m_sz = sz;
427 m_curr = &m_main;
428 }
429
430 //
431 // Thread entry point. Invokes the function or delegate passed on
432 // construction (if any).
433 //
434 package final void run()
435 {
436 m_call();
437 }
438
439 package:
440
441 //
442 // Local storage
443 //
444 static ThreadBase sm_this;
445
446
447 //
448 // Main process thread
449 //
450 __gshared ThreadBase sm_main;
451
452
453 //
454 // Standard thread data
455 //
456 ThreadID m_addr;
457 Callable m_call;
458 string m_name;
459 size_t m_sz;
460 bool m_isDaemon;
461 Throwable m_unhandled;
462
463 ///////////////////////////////////////////////////////////////////////////
464 // Storage of Active Thread
465 ///////////////////////////////////////////////////////////////////////////
466
467
468 //
469 // Sets a thread-local reference to the current thread object.
470 //
471 package static void setThis(ThreadBase t) nothrow @nogc
472 {
473 sm_this = t;
474 }
475
476 package(core.thread):
477
478 StackContext m_main;
479 StackContext* m_curr;
480 bool m_lock;
481 private void* m_tlsgcdata;
482 private void* m_tlsrtdata;
483
484 ///////////////////////////////////////////////////////////////////////////
485 // Thread Context and GC Scanning Support
486 ///////////////////////////////////////////////////////////////////////////
487
488
489 final void pushContext(StackContext* c) nothrow @nogc
490 in
491 {
492 assert(!c.within);
493 }
494 do
495 {
496 m_curr.ehContext = swapContext(c.ehContext);
497 c.within = m_curr;
498 m_curr = c;
499 }
500
501
502 final void popContext() nothrow @nogc
503 in
504 {
505 assert(m_curr && m_curr.within);
506 }
507 do
508 {
509 StackContext* c = m_curr;
510 m_curr = c.within;
511 c.ehContext = swapContext(m_curr.ehContext);
512 c.within = null;
513 }
514
515 private final StackContext* topContext() nothrow @nogc
516 in(m_curr)
517 {
518 return m_curr;
519 }
520
521
522 package(core.thread):
523 ///////////////////////////////////////////////////////////////////////////
524 // GC Scanning Support
525 ///////////////////////////////////////////////////////////////////////////
526
527
528 // NOTE: The GC scanning process works like so:
529 //
530 // 1. Suspend all threads.
531 // 2. Scan the stacks of all suspended threads for roots.
532 // 3. Resume all threads.
533 //
534 // Step 1 and 3 require a list of all threads in the system, while
535 // step 2 requires a list of all thread stacks (each represented by
536 // a Context struct). Traditionally, there was one stack per thread
537 // and the Context structs were not necessary. However, Fibers have
538 // changed things so that each thread has its own 'main' stack plus
539 // an arbitrary number of nested stacks (normally referenced via
540 // m_curr). Also, there may be 'free-floating' stacks in the system,
541 // which are Fibers that are not currently executing on any specific
542 // thread but are still being processed and still contain valid
543 // roots.
544 //
545 // To support all of this, the Context struct has been created to
546 // represent a stack range, and a global list of Context structs has
547 // been added to enable scanning of these stack ranges. The lifetime
548 // (and presence in the Context list) of a thread's 'main' stack will
549 // be equivalent to the thread's lifetime. So the Ccontext will be
550 // added to the list on thread entry, and removed from the list on
551 // thread exit (which is essentially the same as the presence of a
552 // Thread object in its own global list). The lifetime of a Fiber's
553 // context, however, will be tied to the lifetime of the Fiber object
554 // itself, and Fibers are expected to add/remove their Context struct
555 // on construction/deletion.
556
557
558 //
559 // All use of the global thread lists/array should synchronize on this lock.
560 //
561 // Careful as the GC acquires this lock after the GC lock to suspend all
562 // threads any GC usage with slock held can result in a deadlock through
563 // lock order inversion.
564 @property static Mutex slock() nothrow @nogc
565 {
566 return cast(Mutex)_slock.ptr;
567 }
568
569 __gshared align(mutexAlign) void[mutexClassInstanceSize] _slock;
570
571 static void initLocks() @nogc nothrow
572 {
573 import core.lifetime : emplace;
574 emplace!Mutex(_slock[]);
575 }
576
577 static void termLocks() @nogc nothrow
578 {
579 (cast(Mutex)_slock.ptr).__dtor();
580 }
581
582 __gshared StackContext* sm_cbeg;
583
584 __gshared ThreadBase sm_tbeg;
585 __gshared size_t sm_tlen;
586
587 // can't use core.internal.util.array in public code
588 private __gshared ThreadBase* pAboutToStart;
589 private __gshared size_t nAboutToStart;
590
591 //
592 // Used for ordering threads in the global thread list.
593 //
594 ThreadBase prev;
595 ThreadBase next;
596
597
598 ///////////////////////////////////////////////////////////////////////////
599 // Global Context List Operations
600 ///////////////////////////////////////////////////////////////////////////
601
602
603 //
604 // Add a context to the global context list.
605 //
606 static void add(StackContext* c) nothrow @nogc
607 in
608 {
609 assert(c);
610 assert(!c.next && !c.prev);
611 }
612 do
613 {
614 slock.lock_nothrow();
615 scope(exit) slock.unlock_nothrow();
616 assert(!suspendDepth); // must be 0 b/c it's only set with slock held
617
618 if (sm_cbeg)
619 {
620 c.next = sm_cbeg;
621 sm_cbeg.prev = c;
622 }
623 sm_cbeg = c;
624 }
625
626 //
627 // Remove a context from the global context list.
628 //
629 // This assumes slock being acquired. This isn't done here to
630 // avoid double locking when called from remove(Thread)
631 static void remove(StackContext* c) nothrow @nogc
632 in
633 {
634 assert(c);
635 assert(c.next || c.prev);
636 }
637 do
638 {
639 if (c.prev)
640 c.prev.next = c.next;
641 if (c.next)
642 c.next.prev = c.prev;
643 if (sm_cbeg == c)
644 sm_cbeg = c.next;
645 // NOTE: Don't null out c.next or c.prev because opApply currently
646 // follows c.next after removing a node. This could be easily
647 // addressed by simply returning the next node from this
648 // function, however, a context should never be re-added to the
649 // list anyway and having next and prev be non-null is a good way
650 // to ensure that.
651 }
652
653
654 ///////////////////////////////////////////////////////////////////////////
655 // Global Thread List Operations
656 ///////////////////////////////////////////////////////////////////////////
657
658 package static void incrementAboutToStart(ThreadBase t) nothrow @nogc
659 {
660 ++nAboutToStart;
661 pAboutToStart = cast(ThreadBase*)realloc(pAboutToStart, ThreadBase.sizeof * nAboutToStart);
662 pAboutToStart[nAboutToStart - 1] = t;
663 }
664
665 //
666 // Add a thread to the global thread list.
667 //
668 static void add(ThreadBase t, bool rmAboutToStart = true) nothrow @nogc
669 in
670 {
671 assert(t);
672 assert(!t.next && !t.prev);
673 }
674 do
675 {
676 slock.lock_nothrow();
677 scope(exit) slock.unlock_nothrow();
678 assert(t.isRunning); // check this with slock to ensure pthread_create already returned
679 assert(!suspendDepth); // must be 0 b/c it's only set with slock held
680
681 if (rmAboutToStart)
682 {
683 size_t idx = -1;
684 foreach (i, thr; pAboutToStart[0 .. nAboutToStart])
685 {
686 if (thr is t)
687 {
688 idx = i;
689 break;
690 }
691 }
692 assert(idx != -1);
693 import core.stdc.string : memmove;
694 memmove(pAboutToStart + idx, pAboutToStart + idx + 1, size_t.sizeof * (nAboutToStart - idx - 1));
695 pAboutToStart =
696 cast(ThreadBase*)realloc(pAboutToStart, size_t.sizeof * --nAboutToStart);
697 }
698
699 if (sm_tbeg)
700 {
701 t.next = sm_tbeg;
702 sm_tbeg.prev = t;
703 }
704 sm_tbeg = t;
705 ++sm_tlen;
706 }
707
708
709 //
710 // Remove a thread from the global thread list.
711 //
712 static void remove(ThreadBase t) nothrow @nogc
713 in
714 {
715 assert(t);
716 }
717 do
718 {
719 // Thread was already removed earlier, might happen b/c of thread_detachInstance
720 if (!t.next && !t.prev && (sm_tbeg !is t))
721 return;
722
723 slock.lock_nothrow();
724 {
725 // NOTE: When a thread is removed from the global thread list its
726 // main context is invalid and should be removed as well.
727 // It is possible that t.m_curr could reference more
728 // than just the main context if the thread exited abnormally
729 // (if it was terminated), but we must assume that the user
730 // retains a reference to them and that they may be re-used
731 // elsewhere. Therefore, it is the responsibility of any
732 // object that creates contexts to clean them up properly
733 // when it is done with them.
734 remove(&t.m_main);
735
736 if (t.prev)
737 t.prev.next = t.next;
738 if (t.next)
739 t.next.prev = t.prev;
740 if (sm_tbeg is t)
741 sm_tbeg = t.next;
742 t.prev = t.next = null;
743 --sm_tlen;
744 }
745 // NOTE: Don't null out t.next or t.prev because opApply currently
746 // follows t.next after removing a node. This could be easily
747 // addressed by simply returning the next node from this
748 // function, however, a thread should never be re-added to the
749 // list anyway and having next and prev be non-null is a good way
750 // to ensure that.
751 slock.unlock_nothrow();
752 }
753
754 //
755 // Add a thread to the global thread list, and also register This thread
756 // for use in `getThis`. This does both operations while protected by the
757 // static lock. This helps alternative GCs that use `thread_preSuspend` to
758 // determine whether druntime will provide scanning details during
759 // `thread_scanAll`. Without holding the lock for both operations, it's
760 // possible a `thread_preSuspend` would return true, but the scanning
761 // details would not be handled.
762 //
763 static void registerThis(ThreadBase t, bool rmAboutToStart = true) nothrow @nogc
764 {
765 slock.lock_nothrow();
766 scope(exit) slock.unlock_nothrow();
767
768 setThis(t);
769 add(t, rmAboutToStart);
770 }
771
772 }
773
774
775 ///////////////////////////////////////////////////////////////////////////////
776 // GC Support Routines
777 ///////////////////////////////////////////////////////////////////////////////
778
779 private alias attachThread = externDFunc!("core.thread.osthread.attachThread", ThreadBase function(ThreadBase) @nogc nothrow);
780
781 extern (C) void _d_monitordelete_nogc(Object h) @nogc nothrow;
782
783 /**
784 * Terminates the thread module. No other thread routine may be called
785 * afterwards.
786 */
787 package void thread_term_tpl(ThreadT, MainThreadStore)(ref MainThreadStore _mainThreadStore) @nogc nothrow
788 {
789 assert(_mainThreadStore.ptr is cast(void*) ThreadBase.sm_main);
790
791 // destruct manually as object.destroy is not @nogc
792 (cast(ThreadT) cast(void*) ThreadBase.sm_main).__dtor();
793 _d_monitordelete_nogc(ThreadBase.sm_main);
794 _mainThreadStore[] = cast(void[]) __traits(initSymbol, ThreadT)[];
795 ThreadBase.sm_main = null;
796
797 assert(ThreadBase.sm_tbeg && ThreadBase.sm_tlen == 1);
798 assert(!ThreadBase.nAboutToStart);
799 if (ThreadBase.pAboutToStart) // in case realloc(p, 0) doesn't return null
800 {
801 free(ThreadBase.pAboutToStart);
802 ThreadBase.pAboutToStart = null;
803 }
804 ThreadBase.termLocks();
805 termLowlevelThreads();
806 }
807
808
809 /**
810 *
811 */
812 extern (C) bool thread_isMainThread() nothrow @nogc
813 {
814 return ThreadBase.getThis() is ThreadBase.sm_main;
815 }
816
817
818 /**
819 * Registers the calling thread for use with the D Runtime. If this routine
820 * is called for a thread which is already registered, no action is performed.
821 *
822 * NOTE: This routine does not run thread-local static constructors when called.
823 * If full functionality as a D thread is desired, the following function
824 * must be called after thread_attachThis:
825 *
826 * extern (C) void rt_moduleTlsCtor();
827 */
828 package ThreadT thread_attachThis_tpl(ThreadT)()
829 {
830 if (auto t = ThreadT.getThis())
831 return t;
832
833 return cast(ThreadT) attachThread(new ThreadT());
834 }
835
836
837 /**
838 * Deregisters the calling thread from use with the runtime. If this routine
839 * is called for a thread which is not registered, the result is undefined.
840 *
841 * NOTE: This routine does not run thread-local static destructors when called.
842 * If full functionality as a D thread is desired, the following function
843 * must be called before thread_detachThis, particularly if the thread is
844 * being detached at some indeterminate time before program termination:
845 *
846 * $(D extern(C) void rt_moduleTlsDtor();)
847 *
848 * See_Also:
849 * $(REF thread_attachThis, core,thread,osthread)
850 */
851 extern (C) void thread_detachThis() nothrow @nogc
852 {
853 if (auto t = ThreadBase.getThis())
854 ThreadBase.remove(t);
855 }
856
857
858 /**
859 * Deregisters the given thread from use with the runtime. If this routine
860 * is called for a thread which is not registered, the result is undefined.
861 *
862 * NOTE: This routine does not run thread-local static destructors when called.
863 * If full functionality as a D thread is desired, the following function
864 * must be called by the detached thread, particularly if the thread is
865 * being detached at some indeterminate time before program termination:
866 *
867 * $(D extern(C) void rt_moduleTlsDtor();)
868 */
869 extern (C) void thread_detachByAddr(ThreadID addr)
870 {
871 if (auto t = thread_findByAddr(addr))
872 ThreadBase.remove(t);
873 }
874
875
876 /// ditto
877 extern (C) void thread_detachInstance(ThreadBase t) nothrow @nogc
878 {
879 ThreadBase.remove(t);
880 }
881
882
883 /**
884 * Search the list of all threads for a thread with the given thread identifier.
885 *
886 * Params:
887 * addr = The thread identifier to search for.
888 * Returns:
889 * The thread object associated with the thread identifier, null if not found.
890 */
891 static ThreadBase thread_findByAddr(ThreadID addr)
892 {
893 ThreadBase.slock.lock_nothrow();
894 scope(exit) ThreadBase.slock.unlock_nothrow();
895
896 // also return just spawned thread so that
897 // DLL_THREAD_ATTACH knows it's a D thread
898 foreach (t; ThreadBase.pAboutToStart[0 .. ThreadBase.nAboutToStart])
899 if (t.m_addr == addr)
900 return t;
901
902 foreach (t; ThreadBase)
903 if (t.m_addr == addr)
904 return t;
905
906 return null;
907 }
908
909
910 /**
911 * Sets the current thread to a specific reference. Only to be used
912 * when dealing with externally-created threads (in e.g. C code).
913 * The primary use of this function is when ThreadBase.getThis() must
914 * return a sensible value in, for example, TLS destructors. In
915 * other words, don't touch this unless you know what you're doing.
916 *
917 * Params:
918 * t = A reference to the current thread. May be null.
919 */
920 extern (C) void thread_setThis(ThreadBase t) nothrow @nogc
921 {
922 ThreadBase.setThis(t);
923 }
924
925
926 /**
927 * Joins all non-daemon threads that are currently running. This is done by
928 * performing successive scans through the thread list until a scan consists
929 * of only daemon threads.
930 */
931 extern (C) void thread_joinAll()
932 {
933 Lagain:
934 ThreadBase.slock.lock_nothrow();
935 // wait for just spawned threads
936 if (ThreadBase.nAboutToStart)
937 {
938 ThreadBase.slock.unlock_nothrow();
939 ThreadBase.yield();
940 goto Lagain;
941 }
942
943 // join all non-daemon threads, the main thread is also a daemon
944 auto t = ThreadBase.sm_tbeg;
945 while (t)
946 {
947 if (!t.isRunning)
948 {
949 auto tn = t.next;
950 ThreadBase.remove(t);
951 t = tn;
952 }
953 else if (t.isDaemon)
954 {
955 t = t.next;
956 }
957 else
958 {
959 ThreadBase.slock.unlock_nothrow();
960 t.join(); // might rethrow
961 goto Lagain; // must restart iteration b/c of unlock
962 }
963 }
964 ThreadBase.slock.unlock_nothrow();
965 }
966
967
968 /**
969 * Performs intermediate shutdown of the thread module.
970 */
971 shared static ~this()
972 {
973 // NOTE: The functionality related to garbage collection must be minimally
974 // operable after this dtor completes. Therefore, only minimal
975 // cleanup may occur.
976 auto t = ThreadBase.sm_tbeg;
977 while (t)
978 {
979 auto tn = t.next;
980 if (!t.isRunning)
981 ThreadBase.remove(t);
982 t = tn;
983 }
984 }
985
986 // Used for needLock below.
987 package __gshared bool multiThreadedFlag = false;
988
989 // Used for suspendAll/resumeAll below.
990 package __gshared uint suspendDepth = 0;
991
992 private alias resume = externDFunc!("core.thread.osthread.resume", void function(ThreadBase) nothrow @nogc);
993
994 /**
995 * Run the necessary operation required after the world was resumed.
996 */
997 extern (C) void thread_postRestartTheWorld() nothrow {
998 ThreadBase.slock.unlock_nothrow();
999 }
1000
1001 /**
1002 * Resume all threads but the calling thread for "stop the world" garbage
1003 * collection runs. This function must be called once for each preceding
1004 * call to thread_suspendAll before the threads are actually resumed.
1005 *
1006 * In:
1007 * This routine must be preceded by a call to thread_suspendAll.
1008 *
1009 * Throws:
1010 * ThreadError if the resume operation fails for a running thread.
1011 */
1012 extern (C) void thread_resumeAll() nothrow
1013 in
1014 {
1015 assert(suspendDepth > 0);
1016 }
1017 do
1018 {
1019 // NOTE: See thread_suspendAll for the logic behind this.
1020 if (!multiThreadedFlag && ThreadBase.sm_tbeg)
1021 {
1022 if (--suspendDepth == 0)
1023 resume(ThreadBase.getThis());
1024 return;
1025 }
1026
1027 scope(exit) thread_postRestartTheWorld();
1028 {
1029 if (--suspendDepth > 0)
1030 return;
1031
1032 for (ThreadBase t = ThreadBase.sm_tbeg; t; t = t.next)
1033 {
1034 // NOTE: We do not need to care about critical regions at all
1035 // here. thread_suspendAll takes care of everything.
1036 resume(t);
1037 }
1038 }
1039 }
1040
1041 /**
1042 * Indicates the kind of scan being performed by $(D thread_scanAllType).
1043 */
1044 enum ScanType
1045 {
1046 stack, /// The stack and/or registers are being scanned.
1047 tls, /// TLS data is being scanned.
1048 }
1049
1050 alias ScanAllThreadsFn = void delegate(void*, void*) nothrow; /// The scanning function.
1051 alias ScanAllThreadsTypeFn = void delegate(ScanType, void*, void*) nothrow; /// ditto
1052
1053 /**
1054 * The main entry point for garbage collection. The supplied delegate
1055 * will be passed ranges representing both stack and register values.
1056 *
1057 * Params:
1058 * scan = The scanner function. It should scan from p1 through p2 - 1.
1059 *
1060 * In:
1061 * This routine must be preceded by a call to thread_suspendAll.
1062 */
1063 extern (C) void thread_scanAllType(scope ScanAllThreadsTypeFn scan) nothrow
1064 in
1065 {
1066 assert(suspendDepth > 0);
1067 }
1068 do
1069 {
1070 callWithStackShell(sp => scanAllTypeImpl(scan, sp));
1071 }
1072
1073 package alias callWithStackShellDg = void delegate(void* sp) nothrow;
1074 private alias callWithStackShell = externDFunc!("core.thread.osthread.callWithStackShell", void function(scope callWithStackShellDg) nothrow);
1075
1076 private void scanAllTypeImpl(scope ScanAllThreadsTypeFn scan, void* curStackTop) nothrow
1077 {
1078 ThreadBase thisThread = null;
1079 void* oldStackTop = null;
1080
1081 if (ThreadBase.sm_tbeg)
1082 {
1083 thisThread = ThreadBase.getThis();
1084 if (!thisThread.m_lock)
1085 {
1086 oldStackTop = thisThread.m_curr.tstack;
1087 thisThread.m_curr.tstack = curStackTop;
1088 }
1089 }
1090
1091 scope(exit)
1092 {
1093 if (ThreadBase.sm_tbeg)
1094 {
1095 if (!thisThread.m_lock)
1096 {
1097 thisThread.m_curr.tstack = oldStackTop;
1098 }
1099 }
1100 }
1101
1102 // NOTE: Synchronizing on ThreadBase.slock is not needed because this
1103 // function may only be called after all other threads have
1104 // been suspended from within the same lock.
1105 if (ThreadBase.nAboutToStart)
1106 scan(ScanType.stack, ThreadBase.pAboutToStart, ThreadBase.pAboutToStart + ThreadBase.nAboutToStart);
1107
1108 for (StackContext* c = ThreadBase.sm_cbeg; c; c = c.next)
1109 {
1110 static if (isStackGrowingDown)
1111 {
1112 assert(c.tstack <= c.bstack, "stack bottom can't be less than top");
1113
1114 // NOTE: We can't index past the bottom of the stack
1115 // so don't do the "+1" if isStackGrowingDown.
1116 if (c.tstack && c.tstack < c.bstack)
1117 scan(ScanType.stack, c.tstack, c.bstack);
1118 }
1119 else
1120 {
1121 assert(c.bstack <= c.tstack, "stack top can't be less than bottom");
1122
1123 if (c.bstack && c.bstack < c.tstack)
1124 scan(ScanType.stack, c.bstack, c.tstack + 1);
1125 }
1126 }
1127
1128 for (ThreadBase t = ThreadBase.sm_tbeg; t; t = t.next)
1129 {
1130 version (Windows)
1131 {
1132 // Ideally, we'd pass ScanType.regs or something like that, but this
1133 // would make portability annoying because it only makes sense on Windows.
1134 scanWindowsOnly(scan, t);
1135 }
1136
1137 if (t.m_tlsrtdata !is null)
1138 rt_tlsgc_scan(t.m_tlsrtdata, (p1, p2) => scan(ScanType.tls, p1, p2));
1139 }
1140 }
1141
1142 version (Windows)
1143 {
1144 // Currently scanWindowsOnly can't be handled properly by externDFunc
1145 // https://github.com/dlang/druntime/pull/3135#issuecomment-643673218
1146 pragma(mangle, "_D4core6thread8osthread15scanWindowsOnlyFNbMDFNbEQBvQBt10threadbase8ScanTypePvQcZvCQDdQDbQBi10ThreadBaseZv")
1147 private extern (D) void scanWindowsOnly(scope ScanAllThreadsTypeFn scan, ThreadBase) nothrow;
1148 }
1149
1150 /**
1151 * The main entry point for garbage collection. The supplied delegate
1152 * will be passed ranges representing both stack and register values.
1153 *
1154 * Params:
1155 * scan = The scanner function. It should scan from p1 through p2 - 1.
1156 *
1157 * In:
1158 * This routine must be preceded by a call to thread_suspendAll.
1159 */
1160 extern (C) void thread_scanAll(scope ScanAllThreadsFn scan) nothrow
1161 {
1162 thread_scanAllType((type, p1, p2) => scan(p1, p2));
1163 }
1164
1165 private alias thread_yield = externDFunc!("core.thread.osthread.thread_yield", void function() @nogc nothrow);
1166
1167
1168 /**
1169 * A callback for thread errors in D during collections. Since an allocation is not possible
1170 * a preallocated ThreadError will be used as the Error instance
1171 *
1172 * Returns:
1173 * never returns
1174 * Throws:
1175 * ThreadError.
1176 */
1177 package void onThreadError(string msg) nothrow @nogc
1178 {
1179 __gshared ThreadError error = new ThreadError(null);
1180 error.msg = msg;
1181 error.next = null;
1182 import core.exception : SuppressTraceInfo;
1183 error.info = SuppressTraceInfo.instance;
1184 throw error;
1185 }
1186
1187
1188 // GC-specific processing of TLSGC data.
1189 alias ProcessTLSGCDataDg = void* delegate(void* data) nothrow;
1190
1191 void thread_processTLSGCData(ProcessTLSGCDataDg dg) nothrow
1192 {
1193 for (ThreadBase t = ThreadBase.sm_tbeg; t; t = t.next)
1194 t.m_tlsgcdata = dg(t.m_tlsgcdata);
1195 }
1196
1197 /**
1198 * Returns the stack top of the currently active stack within the calling
1199 * thread.
1200 *
1201 * In:
1202 * The calling thread must be attached to the runtime.
1203 *
1204 * Returns:
1205 * The address of the stack top.
1206 */
1207 extern (C) void* thread_stackTop() nothrow @nogc
1208 in
1209 {
1210 // Not strictly required, but it gives us more flexibility.
1211 assert(ThreadBase.getThis());
1212 }
1213 do
1214 {
1215 return getStackTop();
1216 }
1217
1218
1219 /**
1220 * Returns the stack bottom of the currently active stack within the calling
1221 * thread.
1222 *
1223 * In:
1224 * The calling thread must be attached to the runtime.
1225 *
1226 * Returns:
1227 * The address of the stack bottom.
1228 */
1229 extern (C) void* thread_stackBottom() nothrow @nogc
1230 in (ThreadBase.getThis())
1231 {
1232 return ThreadBase.getThis().topContext().bstack;
1233 }
1234
1235
1236 ///////////////////////////////////////////////////////////////////////////////
1237 // lowlovel threading support
1238 ///////////////////////////////////////////////////////////////////////////////
1239 package
1240 {
1241 __gshared size_t ll_nThreads;
1242 __gshared ll_ThreadData* ll_pThreads;
1243
1244 __gshared align(mutexAlign) void[mutexClassInstanceSize] ll_lock;
1245
1246 @property Mutex lowlevelLock() nothrow @nogc
1247 {
1248 return cast(Mutex)ll_lock.ptr;
1249 }
1250
1251 void initLowlevelThreads() @nogc nothrow
1252 {
1253 import core.lifetime : emplace;
1254 emplace(lowlevelLock());
1255 }
1256
1257 void termLowlevelThreads() @nogc nothrow
1258 {
1259 lowlevelLock.__dtor();
1260 }
1261
1262 void ll_removeThread(ThreadID tid) nothrow @nogc
1263 {
1264 lowlevelLock.lock_nothrow();
1265 scope(exit) lowlevelLock.unlock_nothrow();
1266
1267 foreach (i; 0 .. ll_nThreads)
1268 {
1269 if (tid is ll_pThreads[i].tid)
1270 {
1271 import core.stdc.string : memmove;
1272 memmove(ll_pThreads + i, ll_pThreads + i + 1, ll_ThreadData.sizeof * (ll_nThreads - i - 1));
1273 --ll_nThreads;
1274 // no need to minimize, next add will do
1275 break;
1276 }
1277 }
1278 }
1279 }
1280
1281 /**
1282 * Check whether a thread was created by `createLowLevelThread`.
1283 *
1284 * Params:
1285 * tid = the platform specific thread ID.
1286 *
1287 * Returns: `true` if the thread was created by `createLowLevelThread` and is still running.
1288 */
1289 bool findLowLevelThread(ThreadID tid) nothrow @nogc
1290 {
1291 lowlevelLock.lock_nothrow();
1292 scope(exit) lowlevelLock.unlock_nothrow();
1293
1294 foreach (i; 0 .. ll_nThreads)
1295 if (tid is ll_pThreads[i].tid)
1296 return true;
1297 return false;
1298 }