2 * Win32 implementation for mutex/cond/thread functions
4 * Copyright Red Hat, Inc. 2010
7 * Paolo Bonzini <pbonzini@redhat.com>
9 * This work is licensed under the terms of the GNU GPL, version 2 or later.
10 * See the COPYING file in the top-level directory.
13 #include "qemu-common.h"
14 #include "qemu/thread.h"
15 #include "qemu/notify.h"
20 static bool name_threads
;
22 void qemu_thread_naming(bool enable
)
24 /* But note we don't actually name them on Windows yet */
25 name_threads
= enable
;
27 fprintf(stderr
, "qemu: thread naming not supported on this host\n");
30 static void error_exit(int err
, const char *msg
)
34 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER
,
35 NULL
, err
, 0, (LPTSTR
)&pstr
, 2, NULL
);
36 fprintf(stderr
, "qemu: %s: %s\n", msg
, pstr
);
41 void qemu_mutex_init(QemuMutex
*mutex
)
44 InitializeCriticalSection(&mutex
->lock
);
47 void qemu_mutex_destroy(QemuMutex
*mutex
)
49 assert(mutex
->owner
== 0);
50 DeleteCriticalSection(&mutex
->lock
);
53 void qemu_mutex_lock(QemuMutex
*mutex
)
55 EnterCriticalSection(&mutex
->lock
);
57 /* Win32 CRITICAL_SECTIONs are recursive. Assert that we're not
60 assert(mutex
->owner
== 0);
61 mutex
->owner
= GetCurrentThreadId();
64 int qemu_mutex_trylock(QemuMutex
*mutex
)
68 owned
= TryEnterCriticalSection(&mutex
->lock
);
70 assert(mutex
->owner
== 0);
71 mutex
->owner
= GetCurrentThreadId();
76 void qemu_mutex_unlock(QemuMutex
*mutex
)
78 assert(mutex
->owner
== GetCurrentThreadId());
80 LeaveCriticalSection(&mutex
->lock
);
83 void qemu_cond_init(QemuCond
*cond
)
85 memset(cond
, 0, sizeof(*cond
));
87 cond
->sema
= CreateSemaphore(NULL
, 0, LONG_MAX
, NULL
);
89 error_exit(GetLastError(), __func__
);
91 cond
->continue_event
= CreateEvent(NULL
, /* security */
92 FALSE
, /* auto-reset */
93 FALSE
, /* not signaled */
95 if (!cond
->continue_event
) {
96 error_exit(GetLastError(), __func__
);
100 void qemu_cond_destroy(QemuCond
*cond
)
103 result
= CloseHandle(cond
->continue_event
);
105 error_exit(GetLastError(), __func__
);
107 cond
->continue_event
= 0;
108 result
= CloseHandle(cond
->sema
);
110 error_exit(GetLastError(), __func__
);
115 void qemu_cond_signal(QemuCond
*cond
)
120 * Signal only when there are waiters. cond->waiters is
121 * incremented by pthread_cond_wait under the external lock,
122 * so we are safe about that.
124 if (cond
->waiters
== 0) {
129 * Waiting threads decrement it outside the external lock, but
130 * only if another thread is executing pthread_cond_broadcast and
131 * has the mutex. So, it also cannot be decremented concurrently
132 * with this particular access.
134 cond
->target
= cond
->waiters
- 1;
135 result
= SignalObjectAndWait(cond
->sema
, cond
->continue_event
,
137 if (result
== WAIT_ABANDONED
|| result
== WAIT_FAILED
) {
138 error_exit(GetLastError(), __func__
);
142 void qemu_cond_broadcast(QemuCond
*cond
)
146 * As in pthread_cond_signal, access to cond->waiters and
147 * cond->target is locked via the external mutex.
149 if (cond
->waiters
== 0) {
154 result
= ReleaseSemaphore(cond
->sema
, cond
->waiters
, NULL
);
156 error_exit(GetLastError(), __func__
);
160 * At this point all waiters continue. Each one takes its
161 * slice of the semaphore. Now it's our turn to wait: Since
162 * the external mutex is held, no thread can leave cond_wait,
163 * yet. For this reason, we can be sure that no thread gets
164 * a chance to eat *more* than one slice. OTOH, it means
165 * that the last waiter must send us a wake-up.
167 WaitForSingleObject(cond
->continue_event
, INFINITE
);
170 void qemu_cond_wait(QemuCond
*cond
, QemuMutex
*mutex
)
173 * This access is protected under the mutex.
178 * Unlock external mutex and wait for signal.
179 * NOTE: we've held mutex locked long enough to increment
180 * waiters count above, so there's no problem with
181 * leaving mutex unlocked before we wait on semaphore.
183 qemu_mutex_unlock(mutex
);
184 WaitForSingleObject(cond
->sema
, INFINITE
);
186 /* Now waiters must rendez-vous with the signaling thread and
187 * let it continue. For cond_broadcast this has heavy contention
188 * and triggers thundering herd. So goes life.
190 * Decrease waiters count. The mutex is not taken, so we have
191 * to do this atomically.
193 * All waiters contend for the mutex at the end of this function
194 * until the signaling thread relinquishes it. To ensure
195 * each waiter consumes exactly one slice of the semaphore,
196 * the signaling thread stops until it is told by the last
197 * waiter that it can go on.
199 if (InterlockedDecrement(&cond
->waiters
) == cond
->target
) {
200 SetEvent(cond
->continue_event
);
203 qemu_mutex_lock(mutex
);
206 void qemu_sem_init(QemuSemaphore
*sem
, int init
)
209 sem
->sema
= CreateSemaphore(NULL
, init
, LONG_MAX
, NULL
);
212 void qemu_sem_destroy(QemuSemaphore
*sem
)
214 CloseHandle(sem
->sema
);
217 void qemu_sem_post(QemuSemaphore
*sem
)
219 ReleaseSemaphore(sem
->sema
, 1, NULL
);
222 int qemu_sem_timedwait(QemuSemaphore
*sem
, int ms
)
224 int rc
= WaitForSingleObject(sem
->sema
, ms
);
225 if (rc
== WAIT_OBJECT_0
) {
228 if (rc
!= WAIT_TIMEOUT
) {
229 error_exit(GetLastError(), __func__
);
234 void qemu_sem_wait(QemuSemaphore
*sem
)
236 if (WaitForSingleObject(sem
->sema
, INFINITE
) != WAIT_OBJECT_0
) {
237 error_exit(GetLastError(), __func__
);
241 void qemu_event_init(QemuEvent
*ev
, bool init
)
244 ev
->event
= CreateEvent(NULL
, TRUE
, init
, NULL
);
247 void qemu_event_destroy(QemuEvent
*ev
)
249 CloseHandle(ev
->event
);
252 void qemu_event_set(QemuEvent
*ev
)
257 void qemu_event_reset(QemuEvent
*ev
)
259 ResetEvent(ev
->event
);
262 void qemu_event_wait(QemuEvent
*ev
)
264 WaitForSingleObject(ev
->event
, INFINITE
);
267 struct QemuThreadData
{
268 /* Passed to win32_start_routine. */
269 void *(*start_routine
)(void *);
274 /* Only used for joinable threads. */
280 static bool atexit_registered
;
281 static NotifierList main_thread_exit
;
283 static __thread QemuThreadData
*qemu_thread_data
;
285 static void run_main_thread_exit(void)
287 notifier_list_notify(&main_thread_exit
, NULL
);
290 void qemu_thread_atexit_add(Notifier
*notifier
)
292 if (!qemu_thread_data
) {
293 if (!atexit_registered
) {
294 atexit_registered
= true;
295 atexit(run_main_thread_exit
);
297 notifier_list_add(&main_thread_exit
, notifier
);
299 notifier_list_add(&qemu_thread_data
->exit
, notifier
);
303 void qemu_thread_atexit_remove(Notifier
*notifier
)
305 notifier_remove(notifier
);
308 static unsigned __stdcall
win32_start_routine(void *arg
)
310 QemuThreadData
*data
= (QemuThreadData
*) arg
;
311 void *(*start_routine
)(void *) = data
->start_routine
;
312 void *thread_arg
= data
->arg
;
314 qemu_thread_data
= data
;
315 qemu_thread_exit(start_routine(thread_arg
));
319 void qemu_thread_exit(void *arg
)
321 QemuThreadData
*data
= qemu_thread_data
;
323 notifier_list_notify(&data
->exit
, NULL
);
324 if (data
->mode
== QEMU_THREAD_JOINABLE
) {
326 EnterCriticalSection(&data
->cs
);
328 LeaveCriticalSection(&data
->cs
);
335 void *qemu_thread_join(QemuThread
*thread
)
337 QemuThreadData
*data
;
342 if (data
->mode
== QEMU_THREAD_DETACHED
) {
347 * Because multiple copies of the QemuThread can exist via
348 * qemu_thread_get_self, we need to store a value that cannot
349 * leak there. The simplest, non racy way is to store the TID,
350 * discard the handle that _beginthreadex gives back, and
351 * get another copy of the handle here.
353 handle
= qemu_thread_get_handle(thread
);
355 WaitForSingleObject(handle
, INFINITE
);
359 DeleteCriticalSection(&data
->cs
);
364 void qemu_thread_create(QemuThread
*thread
, const char *name
,
365 void *(*start_routine
)(void *),
369 struct QemuThreadData
*data
;
371 data
= g_malloc(sizeof *data
);
372 data
->start_routine
= start_routine
;
375 data
->exited
= false;
376 notifier_list_init(&data
->exit
);
378 if (data
->mode
!= QEMU_THREAD_DETACHED
) {
379 InitializeCriticalSection(&data
->cs
);
382 hThread
= (HANDLE
) _beginthreadex(NULL
, 0, win32_start_routine
,
383 data
, 0, &thread
->tid
);
385 error_exit(GetLastError(), __func__
);
387 CloseHandle(hThread
);
391 void qemu_thread_get_self(QemuThread
*thread
)
393 thread
->data
= qemu_thread_data
;
394 thread
->tid
= GetCurrentThreadId();
397 HANDLE
qemu_thread_get_handle(QemuThread
*thread
)
399 QemuThreadData
*data
;
403 if (data
->mode
== QEMU_THREAD_DETACHED
) {
407 EnterCriticalSection(&data
->cs
);
409 handle
= OpenThread(SYNCHRONIZE
| THREAD_SUSPEND_RESUME
, FALSE
,
414 LeaveCriticalSection(&data
->cs
);
418 bool qemu_thread_is_self(QemuThread
*thread
)
420 return GetCurrentThreadId() == thread
->tid
;