5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 2001 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
20 /* These routines are based on GLib's WIN32 gthread implementation and
21 thus credits should go there. */
24 #include "silcincludes.h"
28 /* Thread structure for WIN32 */
31 SilcThreadStart start_func;
36 static DWROD silc_thread_tls;
38 /* Actual routine that is called by WIN32 when the thread is created.
39 We will call the start_func from here. When this returns the thread
42 int __stdcall silc_thread_win32_start(void *context)
44 SilcWin32Thread thread = (SilcWin32Thread)context;
46 TlsSetValue(silc_thread_tls, context);
47 thread->start_func(thread->context);
53 SilcThread silc_thread_create(SilcThreadStart start_func, void *context,
56 SilcWin32Thread thread;
59 SILC_LOG_DEBUG(("Creating new thread"));
61 thread = silc_calloc(1, sizeof(*thread));
62 thread->start_func = start_func;
63 thread->context = context;
64 thread->waitable = waitable;
65 thread->thread = _beginthreadex(NULL, 0, silc_thread_win32_start,
67 if (!thread->thread) {
68 SILC_LOG_ERROR(("Could not create new thread"));
73 return (SilcThread)thread;
76 void silc_thread_exit(void *exit_value)
78 SilcWin32Thread thread = TlsGetValue(silc_thread_tls);
81 /* If the thread is waitable the memory is freed only in silc_thread_wait
82 by another thread. If not waitable, free it now. */
83 if (!thread->waitable)
85 CloseHandle(thread->thread);
89 TlsSetValue(silc_thread_tls, NULL);
95 SilcThread silc_thread_self(void)
97 SilcWin32Thread self = TlsGetValue(silc_thread_tls);
100 /* This should only happen for the main thread! */
101 HANDLE handle = GetCurrentThread ();
102 HANDLE process = GetCurrentProcess ();
103 self = silc_calloc(1, sizeof(*self));
104 DuplicateHandle(process, handle, process,
105 &self->thread, 0, FALSE,
106 DUPLICATE_SAME_ACCESS);
107 TlsSetValue(silc_thread_tls, self);
110 return (SilcThread)self;
113 bool silc_thread_wait(SilcThread thread, void **exit_value)
115 SILC_LOG_DEBUG(("Waiting for thread %p", thread));
117 if (!thread->waitable)
120 /* The thread is waitable thus we will free all memory after the
121 WaitForSingleObject returns, the thread is destroyed after that. */
122 WaitForSingleObject(thread->thread, INFINITE);
123 CloseHandle(thread->thread);
131 #endif /* SILC_THREADS */