jlaitine commented on code in PR #16194:
URL: https://github.com/apache/nuttx/pull/16194#discussion_r2059160520


##########
sched/semaphore/sem_wait.c:
##########
@@ -86,19 +89,62 @@ int nxsem_wait_slow(FAR sem_t *sem)
 
   /* Check if the lock is available */
 
-  if (atomic_fetch_sub(NXSEM_COUNT(sem), 1) > 0)
+  if (mutex)
+    {
+      uint32_t mholder;
+
+      /* We lock the mutex for us by setting the blocks bit,
+       * this is all that is needed if we block
+       */
+
+      mholder = atomic_fetch_or(NXSEM_MHOLDER(sem), NXSEM_MBLOCKS_BIT);
+      if (NXSEM_MACQUIRED(mholder))
+        {
+          /* htcb gets NULL if
+           * - the only holder did exit (without posting first)
+           * - the mutex was reset before
+           * In both cases we simply acquire the mutex, thus recovering
+           * from these situations.
+           */
+
+          htcb = nxsched_get_tcb(mholder & (~NXSEM_MBLOCKS_BIT));
+        }
+
+      unlocked = htcb == NULL;
+    }
+  else
+    {
+      unlocked = atomic_fetch_sub(NXSEM_COUNT(sem), 1) > 0;
+    }
+
+  if (unlocked)
     {
       /* It is, let the task take the semaphore. */
 
       ret = nxsem_protect_wait(sem);
       if (ret < 0)
         {
-          atomic_fetch_add(NXSEM_COUNT(sem), 1);
+          if (mutex)
+            {
+              atomic_set(NXSEM_MHOLDER(sem), NXSEM_NO_MHOLDER);

Review Comment:
   Nope, I just corrected my reply above. This is the only holder of the mutex 
now, but nxsem_protect_wait failed. So the correct value to restore this is to 
NO_HOLDER. No-one can get in between.
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscr...@nuttx.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to