diff --git a/src/runtime/hexagon/hexagon_thread_manager.cc b/src/runtime/hexagon/hexagon_thread_manager.cc index 3658611cf00d..4f8ddd156b9f 100644 --- a/src/runtime/hexagon/hexagon_thread_manager.cc +++ b/src/runtime/hexagon/hexagon_thread_manager.cc @@ -265,9 +265,15 @@ void HexagonThreadManager::WaitOnThreads() { } void HexagonThreadManager::CheckSemaphore(unsigned syncID) { + // We want the success case to be fast, so do not lock the mutex if (semaphores_.find(syncID) == semaphores_.end()) { - semaphores_[syncID] = reinterpret_cast(malloc(sizeof(qurt_sem_t))); - qurt_sem_init_val(semaphores_[syncID], 0); + // If we don't find it, lock the mutex, make sure it hasn't + // been added by another thread before creating it. + std::lock_guard lock(semaphores_mutex_); + if (semaphores_.find(syncID) == semaphores_.end()) { + semaphores_[syncID] = reinterpret_cast(malloc(sizeof(qurt_sem_t))); + qurt_sem_init_val(semaphores_[syncID], 0); + } } } diff --git a/src/runtime/hexagon/hexagon_thread_manager.h b/src/runtime/hexagon/hexagon_thread_manager.h index c911d1326a39..9bf6bb6efe64 100644 --- a/src/runtime/hexagon/hexagon_thread_manager.h +++ b/src/runtime/hexagon/hexagon_thread_manager.h @@ -213,6 +213,9 @@ class HexagonThreadManager { //! \brief Semaphores used by `Signal` and `Wait` mapped by ID. std::unordered_map semaphores_; + //! \brief Protects updates to semaphores_ + std::mutex semaphores_mutex_; + //! \brief Start semaphore created at time of construction; signled by `Start`. qurt_sem_t start_semaphore_;