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>
This commit is contained in:
Paolo Bonzini
2026-03-30 16:17:15 +02:00
parent 76ad26dd17
commit 55e0216466

View File

@@ -242,7 +242,7 @@ struct QemuThreadData {
/* Only used for joinable threads. */ /* Only used for joinable threads. */
bool exited; bool exited;
void *ret; void *ret;
CRITICAL_SECTION cs; SRWLOCK lock;
}; };
static bool atexit_registered; static bool atexit_registered;
@@ -295,9 +295,9 @@ void qemu_thread_exit(void *arg)
notifier_list_notify(&data->exit, NULL); notifier_list_notify(&data->exit, NULL);
if (data->mode == QEMU_THREAD_JOINABLE) { if (data->mode == QEMU_THREAD_JOINABLE) {
data->ret = arg; data->ret = arg;
EnterCriticalSection(&data->cs); AcquireSRWLockExclusive(&data->lock);
data->exited = true; data->exited = true;
LeaveCriticalSection(&data->cs); ReleaseSRWLockExclusive(&data->lock);
} else { } else {
g_free(data); g_free(data);
} }
@@ -328,7 +328,6 @@ void *qemu_thread_join(QemuThread *thread)
CloseHandle(handle); CloseHandle(handle);
} }
ret = data->ret; ret = data->ret;
DeleteCriticalSection(&data->cs);
g_free(data); g_free(data);
return ret; return ret;
} }
@@ -357,6 +356,7 @@ void qemu_thread_create(QemuThread *thread, const char *name,
struct QemuThreadData *data; struct QemuThreadData *data;
data = g_malloc(sizeof *data); data = g_malloc(sizeof *data);
InitializeSRWLock(&data->lock);
data->start_routine = start_routine; data->start_routine = start_routine;
data->arg = arg; data->arg = arg;
data->mode = mode; data->mode = mode;
@@ -364,10 +364,6 @@ void qemu_thread_create(QemuThread *thread, const char *name,
data->name = g_strdup(name); data->name = g_strdup(name);
notifier_list_init(&data->exit); notifier_list_init(&data->exit);
if (data->mode != QEMU_THREAD_DETACHED) {
InitializeCriticalSection(&data->cs);
}
hThread = (HANDLE) _beginthreadex(NULL, 0, win32_start_routine, hThread = (HANDLE) _beginthreadex(NULL, 0, win32_start_routine,
data, 0, &thread->tid); data, 0, &thread->tid);
if (!hThread) { if (!hThread) {
@@ -406,14 +402,14 @@ HANDLE qemu_thread_get_handle(QemuThread *thread)
return NULL; return NULL;
} }
EnterCriticalSection(&data->cs); AcquireSRWLockExclusive(&data->lock);
if (!data->exited) { if (!data->exited) {
handle = OpenThread(SYNCHRONIZE | THREAD_SUSPEND_RESUME | handle = OpenThread(SYNCHRONIZE | THREAD_SUSPEND_RESUME |
THREAD_SET_CONTEXT, FALSE, thread->tid); THREAD_SET_CONTEXT, FALSE, thread->tid);
} else { } else {
handle = NULL; handle = NULL;
} }
LeaveCriticalSection(&data->cs); ReleaseSRWLockExclusive(&data->lock);
return handle; return handle;
} }