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

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

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

#include 
#include 
#include 
#include 

        
相关标签:
2条回答
  • 2021-02-05 13:06

    You can defend your code against this problem. One easy way is to have one thread whose sole purpose is to watch the system clock. You keep a global linked list of condition variables, and if the clock watcher thread sees a system clock jump, it broadcasts every condition variable on the list. Then, you simply wrap pthread_cond_init and pthread_cond_destroy with code that adds/removes the condition variable to/from the global linked list. Protect the linked list with a mutex.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题