From 86336293a8066b396537fae117d8549460cd85fd Mon Sep 17 00:00:00 2001 From: bjacob Date: Fri, 10 Nov 2023 07:02:20 -0500 Subject: [PATCH] Fix data race (TSan report) on worker thread startup on macOS in `iree_thread_request_affinity` (#15499) TSan report: ``` WARNING: ThreadSanitizer: data race (pid=45817) Read of size 4 at 0x0001084004e0 by thread T2: #0 iree_thread_request_affinity threading_darwin.c:230 (local-task_vmvx_semaphore_submission_test:arm64+0x100078f40) #1 iree_task_worker_main worker.c:385 (local-task_vmvx_semaphore_submission_test:arm64+0x100071594) #2 iree_thread_start_routine threading_darwin.c:72 (local-task_vmvx_semaphore_submission_test:arm64+0x100078e3c) Previous write of size 4 at 0x0001084004e0 by main thread: #0 iree_thread_create threading_darwin.c:140 (local-task_vmvx_semaphore_submission_test:arm64+0x100078ca4) #1 iree_task_worker_initialize worker.c:66 (local-task_vmvx_semaphore_submission_test:arm64+0x1000714f8) #2 iree_task_executor_create executor.c:161 (local-task_vmvx_semaphore_submission_test:arm64+0x10006b2b0) ``` The read of `thread->mach_port` at https://github.com/openxla/iree/blob/ccc4c3719cea467477a783f1c9e9f1fc06b4c508/runtime/src/iree/base/internal/threading_darwin.c#L230 is not ordered relatively to the write of that variable in the parent thread after `pthread_mach_thread_np` returns: https://github.com/openxla/iree/blob/ccc4c3719cea467477a783f1c9e9f1fc06b4c508/runtime/src/iree/base/internal/threading_darwin.c#L140 The proposed fix is that the worker thread shouldn't need to access its own `thread->mach_port`, it can equivalently call `mach_task_self()`. --- runtime/src/iree/base/internal/threading_darwin.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/src/iree/base/internal/threading_darwin.c b/runtime/src/iree/base/internal/threading_darwin.c index 396bda090143..78d0f8f3daf2 100644 --- a/runtime/src/iree/base/internal/threading_darwin.c +++ b/runtime/src/iree/base/internal/threading_darwin.c @@ -227,7 +227,7 @@ void iree_thread_request_affinity(iree_thread_t* thread, // https://fergofrog.com/code/cbowser/xnu/osfmk/mach/thread_policy.h.html // http://www.hybridkernel.com/2015/01/18/binding_threads_to_cores_osx.html thread_affinity_policy_data_t policy_data = {affinity.id}; - thread_policy_set(thread->mach_port, THREAD_AFFINITY_POLICY, + thread_policy_set(mach_task_self(), THREAD_AFFINITY_POLICY, (thread_policy_t)(&policy_data), THREAD_AFFINITY_POLICY_COUNT);