AP_HAL_SITL: fix Semaphore ownership race in give()

give() cleared the owner field after releasing the mutex.  In the window between the unlock and the owner=-1 assignment another thread could take the lock and set itself as owner; we would then clobber that ownership, causing a spurious "Wrong owner" panic when the victim thread next called check_owner().

owner is now cleared while the lock is still held, so it is only ever mutated under lock protection.  This is exercised when two threads share a bus semaphore, e.g. a driver with its own thread and a periodic-callback driver on the same simulated SPI bus.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Peter Barker
2026-07-15 07:43:31 +10:00
committed by Peter Barker
co-authored by Claude Opus 4.8
parent ff89dabe3b
commit cd9c35cd64
+3 -3
View File
@@ -22,12 +22,12 @@ Semaphore::Semaphore()
bool Semaphore::give()
{
take_count--;
if (pthread_mutex_unlock(&_lock) != 0) {
AP_HAL::panic("Bad semaphore usage");
}
if (take_count == 0) {
owner = (pthread_t)-1;
}
if (pthread_mutex_unlock(&_lock) != 0) {
AP_HAL::panic("Bad semaphore usage");
}
return true;
}