How to make pthread_cond_timedwait() robust against system clock manipulations?

前端 未结 2 2025
渐次进展
渐次进展 2021-02-05 12:39

Consider the following source code, which is fully POSIX compliant:

#include 
#include 
#include 
#include 

        
2条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-05 13:09

    Interesting, I've not encountered that behaviour before but, then again, I'm not in the habit of mucking about with my system time that much :-)

    Assuming you're doing that for a valid reason, one possible (though kludgy) solution is to have another thread whose sole purpose is to periodically kick the condition variable to wake up any threads so affected.

    In other words, something like:

    while (1) {
        sleep (10);
        pthread_cond_signal (&condVar);
    }
    

    Your code that's waiting for the condition variable to be kicked should be checking its predicate anyway (to take care of spurious wakeups) so this shouldn't have any real detrimental effect on the functionality.

    It's a slight performance hit but once every ten seconds shouldn't be too much of a problem. It's only really meant to take care of the situations where (for whatever reason) your timed wait will be waiting a long time.


    Another possibility is to re-engineer your application so that you don't need timed waits at all.

    In situations where threads need to be woken for some reason, it's invariably by another thread which is perfectly capable of kicking a condition variable to wake one (or broadcasting to wake the lot of them).

    This is very similar to the kicking thread I mentioned above but more as an integral part of your architecture than a bolt-on.

提交回复
热议问题