2 * threads.c: Thread handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002 Ximian, Inc.
12 #include <mono/os/gc_wrapper.h>
13 #include "mono/utils/mono-hash.h"
23 #include <mono/io-layer/wapi.h>
24 #include <mono/io-layer/wapi-private.h>
25 #include <mono/io-layer/timed-thread.h>
26 #include <mono/io-layer/handles-private.h>
27 #include <mono/io-layer/misc-private.h>
28 #include <mono/io-layer/mono-mutex.h>
29 #include <mono/io-layer/thread-private.h>
30 #include <mono/io-layer/mono-spinlock.h>
34 #undef TLS_PTHREAD_MUTEX
37 /* Hash threads with tids. I thought of using TLS for this, but that
38 * would have to set the data in the new thread, which is more hassle
40 static mono_once_t thread_hash_once = MONO_ONCE_INIT;
41 static mono_mutex_t thread_hash_mutex = MONO_MUTEX_INITIALIZER;
42 static GHashTable *thread_hash=NULL;
45 static MonoGHashTable *tls_gc_hash = NULL;
48 static void thread_close_private (gpointer handle);
49 static void thread_own (gpointer handle);
51 struct _WapiHandleOps _wapi_thread_ops = {
52 NULL, /* close_shared */
53 thread_close_private, /* close_private */
59 static mono_once_t thread_ops_once=MONO_ONCE_INIT;
61 #ifdef WITH_INCLUDED_LIBGC
62 static void gc_init (void);
65 static void thread_ops_init (void)
67 _wapi_handle_register_capabilities (WAPI_HANDLE_THREAD,
68 WAPI_HANDLE_CAP_WAIT);
70 #ifdef WITH_INCLUDED_LIBGC
75 static void thread_close_private (gpointer handle)
77 struct _WapiHandlePrivate_thread *thread_handle;
80 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_THREAD, NULL,
81 (gpointer *)&thread_handle);
83 g_warning (G_GNUC_PRETTY_FUNCTION
84 ": error looking up thread handle %p", handle);
89 g_message(G_GNUC_PRETTY_FUNCTION
90 ": closing thread handle %p with thread %p id %ld",
91 handle, thread_handle->thread,
92 thread_handle->thread->id);
95 if(thread_handle->thread!=NULL) {
96 _wapi_timed_thread_destroy (thread_handle->thread);
100 static void thread_own (gpointer handle)
102 struct _WapiHandle_thread *thread_handle;
103 struct _WapiHandlePrivate_thread *thread_private_handle;
106 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
107 (gpointer *)&thread_handle,
108 (gpointer *)&thread_private_handle);
110 g_warning (G_GNUC_PRETTY_FUNCTION
111 ": error looking up thread handle %p", handle);
115 if(thread_private_handle->joined==FALSE) {
116 _wapi_timed_thread_join (thread_private_handle->thread, NULL,
118 thread_private_handle->joined=TRUE;
122 static void thread_exit(guint32 exitstatus, gpointer handle)
124 struct _WapiHandle_thread *thread_handle;
125 struct _WapiHandlePrivate_thread *thread_private_handle;
128 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
129 (gpointer *)&thread_handle,
130 (gpointer *)&thread_private_handle);
132 g_warning (G_GNUC_PRETTY_FUNCTION
133 ": error looking up thread handle %p", handle);
137 _wapi_handle_lock_handle (handle);
140 g_message (G_GNUC_PRETTY_FUNCTION
141 ": Recording thread handle %p exit status", handle);
144 thread_handle->exitstatus=exitstatus;
145 thread_handle->state=THREAD_STATE_EXITED;
146 _wapi_handle_set_signal_state (handle, TRUE, TRUE);
148 _wapi_handle_unlock_handle (handle);
151 g_message(G_GNUC_PRETTY_FUNCTION
152 ": Recording thread handle %p id %ld status as %d",
153 handle, thread_private_handle->thread->id, exitstatus);
156 /* Remove this thread from the hash */
157 mono_mutex_lock(&thread_hash_mutex);
158 g_hash_table_remove(thread_hash, &thread_private_handle->thread->id);
159 mono_mutex_unlock(&thread_hash_mutex);
161 /* The thread is no longer active, so unref it */
162 _wapi_handle_unref (handle);
165 static void thread_hash_init(void)
167 thread_hash=g_hash_table_new(g_int_hash, g_int_equal);
172 * @security: Ignored for now.
173 * @stacksize: the size in bytes of the new thread's stack. Use 0 to
174 * default to the normal stack size. (Ignored for now).
175 * @start: The function that the new thread should start with
176 * @param: The parameter to give to @start.
177 * @create: If 0, the new thread is ready to run immediately. If
178 * %CREATE_SUSPENDED, the new thread will be in the suspended state,
179 * requiring a ResumeThread() call to continue running.
180 * @tid: If non-NULL, the ID of the new thread is stored here.
182 * Creates a new threading handle.
184 * Return value: a new handle, or NULL
186 gpointer CreateThread(WapiSecurityAttributes *security G_GNUC_UNUSED, guint32 stacksize G_GNUC_UNUSED,
187 WapiThreadStart start, gpointer param, guint32 create,
190 struct _WapiHandle_thread *thread_handle;
191 struct _WapiHandlePrivate_thread *thread_private_handle;
197 mono_once(&thread_hash_once, thread_hash_init);
198 mono_once (&thread_ops_once, thread_ops_init);
204 handle=_wapi_handle_new (WAPI_HANDLE_THREAD);
205 if(handle==_WAPI_HANDLE_INVALID) {
206 g_warning (G_GNUC_PRETTY_FUNCTION
207 ": error creating thread handle");
211 _wapi_handle_lock_handle (handle);
213 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
214 (gpointer *)&thread_handle,
215 (gpointer *)&thread_private_handle);
217 g_warning (G_GNUC_PRETTY_FUNCTION
218 ": error looking up thread handle %p", handle);
219 _wapi_handle_unlock_handle (handle);
223 /* Hold a reference while the thread is active, because we use
224 * the handle to store thread exit information
226 _wapi_handle_ref (handle);
228 thread_handle->state=THREAD_STATE_START;
230 /* Lock around the thread create, so that the new thread cant
231 * race us to look up the thread handle in GetCurrentThread()
233 mono_mutex_lock(&thread_hash_mutex);
235 /* Set a 2M stack size. This is the default on Linux, but BSD
236 * needs it. (The original bug report from Martin Dvorak <md@9ll.cz>
237 * set the size to 2M-4k. I don't know why it's short by 4k, so
238 * I'm leaving it as 2M until I'm told differently.)
240 pthread_attr_init(&attr);
241 pthread_attr_setstacksize(&attr, 1024*1024*2);
243 ret=_wapi_timed_thread_create(&thread_private_handle->thread, &attr,
244 create, start, thread_exit, param,
248 g_message(G_GNUC_PRETTY_FUNCTION ": Thread create error: %s",
251 mono_mutex_unlock(&thread_hash_mutex);
252 _wapi_handle_unlock_handle (handle);
253 _wapi_handle_unref (handle);
255 /* And again, because of the reference we took above */
256 _wapi_handle_unref (handle);
260 g_hash_table_insert(thread_hash, &thread_private_handle->thread->id,
262 mono_mutex_unlock(&thread_hash_mutex);
265 g_message(G_GNUC_PRETTY_FUNCTION
266 ": Started thread handle %p thread %p ID %ld", handle,
267 thread_private_handle->thread,
268 thread_private_handle->thread->id);
272 #ifdef PTHREAD_POINTER_ID
273 *tid=GPOINTER_TO_UINT(thread_private_handle->thread->id);
275 *tid=thread_private_handle->thread->id;
279 _wapi_handle_unlock_handle (handle);
284 gpointer OpenThread (guint32 access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 tid)
288 mono_once(&thread_hash_once, thread_hash_init);
289 mono_once (&thread_ops_once, thread_ops_init);
292 g_message (G_GNUC_PRETTY_FUNCTION ": looking up thread %d", tid);
295 mono_mutex_lock(&thread_hash_mutex);
297 ret=g_hash_table_lookup(thread_hash, &tid);
298 mono_mutex_unlock(&thread_hash_mutex);
301 _wapi_handle_ref (ret);
305 g_message (G_GNUC_PRETTY_FUNCTION ": returning thread handle %p", ret);
313 * @exitcode: Sets the thread's exit code, which can be read from
314 * another thread with GetExitCodeThread().
316 * Terminates the calling thread. A thread can also exit by returning
317 * from its start function. When the last thread in a process
318 * terminates, the process itself terminates.
320 void ExitThread(guint32 exitcode)
322 _wapi_timed_thread_exit(exitcode);
327 * @handle: The thread handle to query
328 * @exitcode: The thread @handle exit code is stored here
330 * Finds the exit code of @handle, and stores it in @exitcode. If the
331 * thread @handle is still running, the value stored is %STILL_ACTIVE.
333 * Return value: %TRUE, or %FALSE on error.
335 gboolean GetExitCodeThread(gpointer handle, guint32 *exitcode)
337 struct _WapiHandle_thread *thread_handle;
338 struct _WapiHandlePrivate_thread *thread_private_handle;
341 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
342 (gpointer *)&thread_handle,
343 (gpointer *)&thread_private_handle);
345 g_warning (G_GNUC_PRETTY_FUNCTION
346 ": error looking up thread handle %p", handle);
351 g_message(G_GNUC_PRETTY_FUNCTION
352 ": Finding exit status for thread handle %p id %ld", handle,
353 thread_private_handle->thread->id);
358 g_message(G_GNUC_PRETTY_FUNCTION
359 ": Nowhere to store exit code");
364 if(thread_handle->state!=THREAD_STATE_EXITED) {
366 g_message(G_GNUC_PRETTY_FUNCTION
367 ": Thread still active (state %d, exited is %d)",
368 thread_handle->state, THREAD_STATE_EXITED);
370 *exitcode=STILL_ACTIVE;
374 *exitcode=thread_handle->exitstatus;
380 * GetCurrentThreadId:
382 * Looks up the thread ID of the current thread. This ID can be
383 * passed to OpenThread() to create a new handle on this thread.
385 * Return value: the thread ID.
387 guint32 GetCurrentThreadId(void)
389 pthread_t tid=pthread_self();
391 #ifdef PTHREAD_POINTER_ID
392 return(GPOINTER_TO_UINT(tid));
398 static gpointer thread_attach(guint32 *tid)
400 struct _WapiHandle_thread *thread_handle;
401 struct _WapiHandlePrivate_thread *thread_private_handle;
406 mono_once(&thread_hash_once, thread_hash_init);
407 mono_once (&thread_ops_once, thread_ops_init);
409 handle=_wapi_handle_new (WAPI_HANDLE_THREAD);
410 if(handle==_WAPI_HANDLE_INVALID) {
411 g_warning (G_GNUC_PRETTY_FUNCTION
412 ": error creating thread handle");
416 _wapi_handle_lock_handle (handle);
418 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
419 (gpointer *)&thread_handle,
420 (gpointer *)&thread_private_handle);
422 g_warning (G_GNUC_PRETTY_FUNCTION
423 ": error looking up thread handle %p", handle);
424 _wapi_handle_unlock_handle (handle);
428 /* Hold a reference while the thread is active, because we use
429 * the handle to store thread exit information
431 _wapi_handle_ref (handle);
433 thread_handle->state=THREAD_STATE_START;
435 /* Lock around the thread create, so that the new thread cant
436 * race us to look up the thread handle in GetCurrentThread()
438 mono_mutex_lock(&thread_hash_mutex);
440 ret=_wapi_timed_thread_attach(&thread_private_handle->thread,
441 thread_exit, handle);
444 g_message(G_GNUC_PRETTY_FUNCTION ": Thread attach error: %s",
447 mono_mutex_unlock(&thread_hash_mutex);
448 _wapi_handle_unlock_handle (handle);
449 _wapi_handle_unref (handle);
451 /* And again, because of the reference we took above */
452 _wapi_handle_unref (handle);
456 g_hash_table_insert(thread_hash, &thread_private_handle->thread->id,
458 mono_mutex_unlock(&thread_hash_mutex);
461 g_message(G_GNUC_PRETTY_FUNCTION
462 ": Attached thread handle %p thread %p ID %ld", handle,
463 thread_private_handle->thread,
464 thread_private_handle->thread->id);
468 #ifdef PTHREAD_POINTER_ID
469 *tid=GPOINTER_TO_UINT(thread_private_handle->thread->id);
471 *tid=thread_private_handle->thread->id;
475 _wapi_handle_unlock_handle (handle);
483 * Looks up the handle associated with the current thread. Under
484 * Windows this is a pseudohandle, and must be duplicated with
485 * DuplicateHandle() for some operations.
487 * Return value: The current thread handle, or %NULL on failure.
488 * (Unknown whether Windows has a possible failure here. It may be
489 * necessary to implement the pseudohandle-constant behaviour).
491 gpointer GetCurrentThread(void)
496 mono_once(&thread_hash_once, thread_hash_init);
497 mono_once (&thread_ops_once, thread_ops_init);
499 tid=GetCurrentThreadId();
501 mono_mutex_lock(&thread_hash_mutex);
503 ret=g_hash_table_lookup(thread_hash, &tid);
504 mono_mutex_unlock(&thread_hash_mutex);
507 ret = thread_attach (NULL);
515 * @handle: the thread handle to resume
517 * Decrements the suspend count of thread @handle. A thread can only
518 * run if its suspend count is zero.
520 * Return value: the previous suspend count, or 0xFFFFFFFF on error.
522 guint32 ResumeThread(gpointer handle)
524 struct _WapiHandle_thread *thread_handle;
525 struct _WapiHandlePrivate_thread *thread_private_handle;
528 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
529 (gpointer *)&thread_handle,
530 (gpointer *)&thread_private_handle);
532 g_warning (G_GNUC_PRETTY_FUNCTION
533 ": error looking up thread handle %p", handle);
537 #ifdef WITH_INCLUDED_LIBGC
538 if (thread_private_handle->thread->suspend_count <= 1)
539 _wapi_timed_thread_resume (thread_private_handle->thread);
541 return --thread_private_handle->thread->suspend_count;
543 /* This is still a kludge that only copes with starting a
544 * thread that was suspended on create, so don't bother with
545 * the suspend count crap yet
547 _wapi_timed_thread_resume (thread_private_handle->thread);
554 * @handle: the thread handle to suspend
556 * Increments the suspend count of thread @handle. A thread can only
557 * run if its suspend count is zero.
559 * Return value: the previous suspend count, or 0xFFFFFFFF on error.
561 guint32 SuspendThread(gpointer handle)
563 #ifdef WITH_INCLUDED_LIBGC
564 struct _WapiHandle_thread *thread_handle;
565 struct _WapiHandlePrivate_thread *thread_private_handle;
569 current = GetCurrentThread ();
570 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
571 (gpointer *)&thread_handle,
572 (gpointer *)&thread_private_handle);
574 g_warning (G_GNUC_PRETTY_FUNCTION
575 ": error looking up thread handle %p", handle);
579 if (!thread_private_handle->thread->suspend_count) {
580 if (handle == current)
581 _wapi_timed_thread_suspend (thread_private_handle->thread);
583 pthread_kill (thread_private_handle->thread->id, SIGPWR);
584 sem_wait (&thread_private_handle->thread->suspended_sem);
588 return thread_private_handle->thread->suspend_count++;
595 * We assume here that TLS_MINIMUM_AVAILABLE is less than
596 * PTHREAD_KEYS_MAX, allowing enough overhead for a few TLS keys for
599 * Currently TLS_MINIMUM_AVAILABLE is 64 and _POSIX_THREAD_KEYS_MAX
600 * (the minimum value for PTHREAD_KEYS_MAX) is 128, so we should be
604 static pthread_key_t TLS_keys[TLS_MINIMUM_AVAILABLE];
605 static gboolean TLS_used[TLS_MINIMUM_AVAILABLE]={FALSE};
606 #ifdef TLS_PTHREAD_MUTEX
607 static mono_mutex_t TLS_mutex=MONO_MUTEX_INITIALIZER;
609 static guint32 TLS_spinlock=0;
615 * Allocates a Thread Local Storage (TLS) index. Any thread in the
616 * same process can use this index to store and retrieve values that
617 * are local to that thread.
619 * Return value: The index value, or %TLS_OUT_OF_INDEXES if no index
622 guint32 TlsAlloc(void)
626 #ifdef TLS_PTHREAD_MUTEX
627 mono_mutex_lock(&TLS_mutex);
629 MONO_SPIN_LOCK (TLS_spinlock);
632 for(i=0; i<TLS_MINIMUM_AVAILABLE; i++) {
633 if(TLS_used[i]==FALSE) {
635 pthread_key_create(&TLS_keys[i], NULL);
637 #ifdef TLS_PTHREAD_MUTEX
638 mono_mutex_unlock(&TLS_mutex);
640 MONO_SPIN_UNLOCK (TLS_spinlock);
644 g_message (G_GNUC_PRETTY_FUNCTION ": returning key %d",
652 #ifdef TLS_PTHREAD_MUTEX
653 mono_mutex_unlock(&TLS_mutex);
655 MONO_SPIN_UNLOCK (TLS_spinlock);
659 g_message (G_GNUC_PRETTY_FUNCTION ": out of indices");
663 return(TLS_OUT_OF_INDEXES);
666 #define MAKE_GC_ID(idx) (GUINT_TO_POINTER((idx)|(GetCurrentThreadId()<<8)))
670 * @idx: The TLS index to free
672 * Releases a TLS index, making it available for reuse. This call
673 * will delete any TLS data stored under index @idx in all threads.
675 * Return value: %TRUE on success, %FALSE otherwise.
677 gboolean TlsFree(guint32 idx)
680 g_message (G_GNUC_PRETTY_FUNCTION ": freeing key %d", idx);
683 #ifdef TLS_PTHREAD_MUTEX
684 mono_mutex_lock(&TLS_mutex);
686 MONO_SPIN_LOCK (TLS_spinlock);
689 if(TLS_used[idx]==FALSE) {
690 #ifdef TLS_PTHREAD_MUTEX
691 mono_mutex_unlock(&TLS_mutex);
693 MONO_SPIN_UNLOCK (TLS_spinlock);
699 pthread_key_delete(TLS_keys[idx]);
702 mono_g_hash_table_remove (tls_gc_hash, MAKE_GC_ID (idx));
705 #ifdef TLS_PTHREAD_MUTEX
706 mono_mutex_unlock(&TLS_mutex);
708 MONO_SPIN_UNLOCK (TLS_spinlock);
716 * @idx: The TLS index to retrieve
718 * Retrieves the TLS data stored under index @idx.
720 * Return value: The value stored in the TLS index @idx in the current
721 * thread, or %NULL on error. As %NULL can be a valid return value,
722 * in this case GetLastError() returns %ERROR_SUCCESS.
724 gpointer TlsGetValue(guint32 idx)
729 g_message (G_GNUC_PRETTY_FUNCTION ": looking up key %d", idx);
732 ret=pthread_getspecific(TLS_keys[idx]);
735 g_message (G_GNUC_PRETTY_FUNCTION ": returning %p", ret);
743 * @idx: The TLS index to store
744 * @value: The value to store under index @idx
746 * Stores @value at TLS index @idx.
748 * Return value: %TRUE on success, %FALSE otherwise.
750 gboolean TlsSetValue(guint32 idx, gpointer value)
755 g_message (G_GNUC_PRETTY_FUNCTION ": setting key %d to %p", idx,
759 #ifdef TLS_PTHREAD_MUTEX
760 mono_mutex_lock(&TLS_mutex);
762 MONO_SPIN_LOCK (TLS_spinlock);
765 if(TLS_used[idx]==FALSE) {
767 g_message (G_GNUC_PRETTY_FUNCTION ": key %d unused", idx);
770 #ifdef TLS_PTHREAD_MUTEX
771 mono_mutex_unlock(&TLS_mutex);
773 MONO_SPIN_UNLOCK (TLS_spinlock);
778 ret=pthread_setspecific(TLS_keys[idx], value);
781 g_message (G_GNUC_PRETTY_FUNCTION
782 ": pthread_setspecific error: %s", strerror (ret));
785 #ifdef TLS_PTHREAD_MUTEX
786 mono_mutex_unlock(&TLS_mutex);
788 MONO_SPIN_UNLOCK (TLS_spinlock);
795 tls_gc_hash = mono_g_hash_table_new(g_direct_hash, g_direct_equal);
796 mono_g_hash_table_insert (tls_gc_hash, MAKE_GC_ID (idx), value);
799 #ifdef TLS_PTHREAD_MUTEX
800 mono_mutex_unlock(&TLS_mutex);
802 MONO_SPIN_UNLOCK (TLS_spinlock);
810 * @ms: The time in milliseconds to suspend for
812 * Suspends execution of the current thread for @ms milliseconds. A
813 * value of zero causes the thread to relinquish its time slice. A
814 * value of %INFINITE causes an infinite delay.
816 void Sleep(guint32 ms)
818 struct timespec req, rem;
823 g_message(G_GNUC_PRETTY_FUNCTION ": Sleeping for %d ms", ms);
831 /* FIXME: check for INFINITE and sleep forever */
832 divvy=div((int)ms, 1000);
834 req.tv_sec=divvy.quot;
835 req.tv_nsec=divvy.rem*1000000;
838 ret=nanosleep(&req, &rem);
840 /* Sleep interrupted with rem time remaining */
842 guint32 rems=rem.tv_sec*1000 + rem.tv_nsec/1000000;
844 g_message(G_GNUC_PRETTY_FUNCTION ": Still got %d ms to go",
852 /* FIXME: implement alertable */
853 void SleepEx(guint32 ms, gboolean alertable)
855 if(alertable==TRUE) {
856 g_warning(G_GNUC_PRETTY_FUNCTION ": alertable not implemented");
862 #ifdef WITH_INCLUDED_LIBGC
864 static void GC_suspend_handler (int sig)
866 struct _WapiHandle_thread *thread_handle;
867 struct _WapiHandlePrivate_thread *thread_private_handle;
871 handle = GetCurrentThread ();
872 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
873 (gpointer *)&thread_handle,
874 (gpointer *)&thread_private_handle);
876 g_warning (G_GNUC_PRETTY_FUNCTION
877 ": error looking up thread handle %p", handle);
881 thread_private_handle->thread->stack_ptr = &ok;
882 sem_post (&thread_private_handle->thread->suspended_sem);
884 _wapi_timed_thread_suspend (thread_private_handle->thread);
886 thread_private_handle->thread->stack_ptr = NULL;
889 static void gc_init (void)
891 struct sigaction act;
893 act.sa_handler = GC_suspend_handler;
894 g_assert (sigaction (SIGPWR, &act, NULL) == 0);
897 void mono_wapi_push_thread_stack (gpointer handle, gpointer stack_ptr)
899 struct _WapiHandle_thread *thread_handle;
900 struct _WapiHandlePrivate_thread *thread_private_handle;
903 ok=_wapi_lookup_handle (handle, WAPI_HANDLE_THREAD,
904 (gpointer *)&thread_handle,
905 (gpointer *)&thread_private_handle);
907 g_warning (G_GNUC_PRETTY_FUNCTION
908 ": error looking up thread handle %p", handle);
912 GC_push_all_stack (thread_private_handle->thread->stack_ptr, stack_ptr);
915 #endif /* WITH_INCLUDED_LIBGC */