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.
22 #include "silcincludes.h"
26 /* Thread structure for WIN32 */
29 SilcThreadStart start_func;
34 static DWORD silc_thread_tls;
36 /* Actual routine that is called by WIN32 when the thread is created.
37 We will call the start_func from here. When this returns the thread
40 unsigned __stdcall silc_thread_win32_start(void *context)
42 SilcWin32Thread thread = (SilcWin32Thread)context;
44 TlsSetValue(silc_thread_tls, context);
45 silc_thread_exit(thread->start_func(thread->context));
51 SilcThread silc_thread_create(SilcThreadStart start_func, void *context,
55 SilcWin32Thread thread;
58 SILC_LOG_DEBUG(("Creating new thread"));
60 thread = silc_calloc(1, sizeof(*thread));
61 thread->start_func = start_func;
62 thread->context = context;
63 thread->waitable = waitable;
64 thread->thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)silc_thread_win32_start, (void *)thread, 0, &id);
66 if (!thread->thread) {
67 SILC_LOG_ERROR(("Could not create new thread"));
72 return (SilcThread)thread;
74 /* Call thread callback immediately */
75 (*start_func)(context);
80 void silc_thread_exit(void *exit_value)
83 SilcWin32Thread thread = TlsGetValue(silc_thread_tls);
86 /* If the thread is waitable the memory is freed only in silc_thread_wait
87 by another thread. If not waitable, free it now. */
88 if (!thread->waitable) {
89 TerminateThread(thread->thread, 0);
93 TlsSetValue(silc_thread_tls, NULL);
99 SilcThread silc_thread_self(void)
102 SilcWin32Thread self = TlsGetValue(silc_thread_tls);
105 /* This should only happen for the main thread! */
106 HANDLE handle = GetCurrentThread ();
107 HANDLE process = GetCurrentProcess ();
108 self = silc_calloc(1, sizeof(*self));
109 DuplicateHandle(process, handle, process,
110 &self->thread, 0, FALSE,
111 DUPLICATE_SAME_ACCESS);
112 TlsSetValue(silc_thread_tls, self);
115 return (SilcThread)self;
121 bool silc_thread_wait(SilcThread thread, void **exit_value)
124 SilcWin32Thread self = (SilcWin32Thread)thread;
126 SILC_LOG_DEBUG(("Waiting for thread %p", self));
131 /* The thread is waitable thus we will free all memory after the
132 WaitForSingleObject returns, the thread is destroyed after that. */
134 /* 2 sec timeout, otherwise we would run to infinite loop some cases.. */
135 if (WaitForSingleObject(self->thread, 2000) == WAIT_TIMEOUT)
136 TerminateThread(self->thread, 0);