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 DWORD 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 unsigned __stdcall silc_thread_win32_start(void *context)
44 SilcWin32Thread thread = (SilcWin32Thread)context;
46 TlsSetValue(silc_thread_tls, context);
47 thread->start_func(thread->context);
48 silc_thread_exit(NULL);
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 = (HANDLE)_beginthreadex(NULL, 0, silc_thread_win32_start,
66 (void *)thread, 0, &id);
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) {
84 CloseHandle(thread->thread);
88 TlsSetValue(silc_thread_tls, NULL);
94 SilcThread silc_thread_self(void)
96 SilcWin32Thread self = TlsGetValue(silc_thread_tls);
99 /* This should only happen for the main thread! */
100 HANDLE handle = GetCurrentThread ();
101 HANDLE process = GetCurrentProcess ();
102 self = silc_calloc(1, sizeof(*self));
103 DuplicateHandle(process, handle, process,
104 &self->thread, 0, FALSE,
105 DUPLICATE_SAME_ACCESS);
106 TlsSetValue(silc_thread_tls, self);
109 return (SilcThread)self;
112 bool silc_thread_wait(SilcThread thread, void **exit_value)
114 SilcWin32Thread self = (SilcWin32Thread)thread;
116 SILC_LOG_DEBUG(("Waiting for thread %p", self));
121 /* The thread is waitable thus we will free all memory after the
122 WaitForSingleObject returns, the thread is destroyed after that. */
123 WaitForSingleObject(self->thread, INFINITE);
124 CloseHandle(self->thread);
132 #endif /* SILC_THREADS */