See previous commit about pthread_mutex_t.
---
 .../winpthreads/src/spinlock.c                | 24 ++++++++++++++++++-
 1 file changed, 23 insertions(+), 1 deletion(-)

diff --git a/mingw-w64-libraries/winpthreads/src/spinlock.c 
b/mingw-w64-libraries/winpthreads/src/spinlock.c
index 9867091c..654136da 100644
--- a/mingw-w64-libraries/winpthreads/src/spinlock.c
+++ b/mingw-w64-libraries/winpthreads/src/spinlock.c
@@ -45,6 +45,12 @@
  *
  * pthread_spin_unlock():
  *  
<https://pubs.opengroup.org/onlinepubs/9799919799.2024edition/functions/pthread_spin_unlock.html>
+ *
+ * Additional reads:
+ *
+ *  [1] LKML - "POSIX mutex destruction requirements vs. futexes"
+ *      -> https://lkml.org/lkml/2014/11/27/472
+ *
  */
 
 /**
@@ -196,7 +202,12 @@ int pthread_spin_init (pthread_spinlock_t *lock, int 
pshared)
 
   wSpinlock->State    = Unlocked;
   wSpinlock->ThreadId = THREAD_ID_NO_OWNER;
-  wSpinlock->Event    = CreateEventW (NULL, FALSE, FALSE, NULL);
+
+  /**
+   * Start in the signaled state to support destruction of spin locks
+   * that have never been contended.  See `pthread_spin_destroy`.
+   */
+  wSpinlock->Event    = CreateEventW (NULL, FALSE, TRUE, NULL);
 
   /**
    * The pthread_spin_init() function shall fail if:
@@ -264,6 +275,12 @@ int pthread_spin_destroy (pthread_spinlock_t *lock)
    */
   InterlockedExchangePointer ((void **) pSpinlock, NULL);
 
+  /**
+   * This function can run concurrently with `pthread_spin_unlock`.
+   * Wait on the event to ensure that `pthread_spin_unlock` has
+   * finished working [1].
+   */
+  _pthread_wait_for_single_object (wSpinlock->Event, INFINITE);
   CloseHandle (wSpinlock->Event);
   free (wSpinlock);
 
@@ -384,6 +401,11 @@ int pthread_spin_unlock (pthread_spinlock_t *lock)
    * waiting for `wSpinlock->Event` to become signaled.
    */
   if (InterlockedExchange (&wSpinlock->State, Unlocked) == LockedWithBlocking) 
{
+    /**
+     * Anything that goes after the exchange to `Unlocked` can run
+     * concurrently with `pthread_spin_destroy` [1]. This is safe
+     * because `pthread_spin_destroy` waits on `mutex->Event`.
+     */
     if (!SetEvent (wSpinlock->Event)) {
       return EINVAL;
     }
-- 
2.55.0.windows.5



_______________________________________________
Mingw-w64-public mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/mingw-w64-public

Reply via email to