Just beware of https://github.com/apache/incubator-nuttx/issues/1352

On 1/13/2021 8:09 AM, Matias N. wrote:
Hi,
thanks for your responses. Yes, upon more reading I realized mixing signals with pthread mutexes was not safe. I guess
I was getting a race condition inside the mutex locking.

As a workaround, I resorted to using SIGEV_THREAD notification for POSIX timers. This appears to work and I guess it should be safe. Eventually I will look into implementing timerfd, if anyone else hasn't done so yet.

Best,
Matias

On Wed, Jan 13, 2021, at 05:52, Juha Niskanen (Haltian) wrote:

    BTW, looking at the spec for pthread_cond_wait, there's actually
    no mention about a limitation regarding using pthread_cond_signal
    invoked from within a signal handler to unblock a pthread_cond_wait.

The restriction is elsewhere. pthread_cond_signal() is not in the list of async-signal-safe functions at

https://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04 <https://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04>

Therefore, portable programs may not call it from a signal handler and except it to work. Asynchronous signal handler can get called between any two instructions so safe synchronization with condition variables might be hard to implement. Use semaphores and sem_post() instead.

-Juha


------------------------------------------------------------------------

*From:* Gregory Nutt <spudan...@gmail.com>
*Sent:* Wednesday, January 13, 2021 4:24 AM
*To:* dev@nuttx.apache.org <dev@nuttx.apache.org>
*Subject:* Re: condition variables and signals


BTW, looking at the spec for pthread_cond_wait, there's actually no mention about a limitation regarding using pthread_cond_signal invoked from within a signal handler to unblock a pthread_cond_wait. However, this does not work either for me. If you follow the signal operation, I can see that when it reaches the nxsem_get_value() on the cond->sem, the semaphore value is zero and the sem_give is not done.


Should this work?

Yes, calling pthread_cond_signal() should work, however, no signal should be delivered.  The word "signal" is overloaded:  Here the condition is signaled but no signal should be sent so I am not quite sure what I am looking at.  Apparently some other logic is signaling the task group asynchronously?

I am thinking that there must be some race condition: When the condition variable is created the cond->sem value will be set to zero.  While waiting for cond->sem, it will be set to -1.  If you see cond->sem equal to zero, my guess would be that the signal was received and cond->sem was incremented asychronously by the signal delivery logic.  But that is only a guess.

It would be good to check the behavior without the signal interfering.





*Attachments:*

  * image.png



Reply via email to