@samitouri / QOSamiQemu / commits / 55e0216466

thread-win32: replace CRITICAL_SECTION with SRWLOCK

SRWLOCK is a much cheaper primitive than CRITICAL_SECTION, which basically exists only as a legacy API. The SRWLOCK is a single word in memory and it is cheaper to just initialize it always. Reviewed-by: Kostiantyn Kostiuk <kkostiuk@redhat.com> Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>

Paolo Bonzini committed Mar 30, 2026 at 16:17 UTC 55e02164666413c8f745534ee5ce3d81e70db0b0
1 file changed +6 -10
util/qemu-thread-win32.c
+6 -10
@@ -242,7 +242,7 @@ struct QemuThreadData {
242 /* Only used for joinable threads. */
243 bool exited;
244 void *ret;
245 - CRITICAL_SECTION cs;
245 + SRWLOCK lock;
246 };
247
248 static bool atexit_registered;
@@ -295,9 +295,9 @@ void qemu_thread_exit(void *arg)
295 notifier_list_notify(&data->exit, NULL);
296 if (data->mode == QEMU_THREAD_JOINABLE) {
297 data->ret = arg;
298 - EnterCriticalSection(&data->cs);
298 + AcquireSRWLockExclusive(&data->lock);
299 data->exited = true;
300 - LeaveCriticalSection(&data->cs);
300 + ReleaseSRWLockExclusive(&data->lock);
301 } else {
302 g_free(data);
303 }
@@ -328,7 +328,6 @@ void *qemu_thread_join(QemuThread *thread)
328 CloseHandle(handle);
329 }
330 ret = data->ret;
331 - DeleteCriticalSection(&data->cs);
331 g_free(data);
332 return ret;
333 }
@@ -357,6 +356,7 @@ void qemu_thread_create(QemuThread *thread, const char *name,
356 struct QemuThreadData *data;
357
358 data = g_malloc(sizeof *data);
359 + InitializeSRWLock(&data->lock);
360 data->start_routine = start_routine;
361 data->arg = arg;
362 data->mode = mode;
@@ -364,10 +364,6 @@ void qemu_thread_create(QemuThread *thread, const char *name,
364 data->name = g_strdup(name);
365 notifier_list_init(&data->exit);
366
367 - if (data->mode != QEMU_THREAD_DETACHED) {
368 - InitializeCriticalSection(&data->cs);
369 - }
370 -
367 hThread = (HANDLE) _beginthreadex(NULL, 0, win32_start_routine,
368 data, 0, &thread->tid);
369 if (!hThread) {
@@ -406,14 +402,14 @@ HANDLE qemu_thread_get_handle(QemuThread *thread)
402 return NULL;
403 }
404
409 - EnterCriticalSection(&data->cs);
405 + AcquireSRWLockExclusive(&data->lock);
406 if (!data->exited) {
407 handle = OpenThread(SYNCHRONIZE | THREAD_SUSPEND_RESUME |
408 THREAD_SET_CONTEXT, FALSE, thread->tid);
409 } else {
410 handle = NULL;
411 }
416 - LeaveCriticalSection(&data->cs);
412 + ReleaseSRWLockExclusive(&data->lock);
413 return handle;
414 }
415