How do I deal with the system clock changing while waiting on a std::condition_variable?

后端 未结 4 1925
抹茶落季
抹茶落季 2020-12-15 06:01

I\'m trying to implement some cross-platform code in C++11. Part of this code implements a semaphore object using a std::condition_variable. When I need to do a timed wait

4条回答
  •  忘掉有多难
    2020-12-15 06:21

    This may not be the best solution, or a great solution, but you did say "work around" and not "a lot of work", so:

    • Use your distribution's facilities to monitor changes to the system clock (I'm not quite sure what these facilities are; at worst, you can run a cron job every 5 minutes to check the clock is around its expected value).
    • Upon detection of a system clock change, communicate something to the process in which you have your waiting/sleeping threads. You might use a signal; or a pipe; or a unix-domain socket; or even some shared memory.
    • On the process' side, make sure you receive this (i.e. write a signal handler, or have a thread doing blocking I/O on the pipe; or polling the shared memory using non-std::condition_variable sleep - respectively)
    • Upon receiving notification regarding a change to the system clock, shake things up in your process, awaken sleeping threads, and re-assess what needs to be done based on the altered time. Maybe it's exactly the same as before, in which case you simply have your threads using the condition variable again.

    Not very elegant, and there's a bunch of overhead involved - but this does make sense, and isn't some crazy hack.

提交回复
热议问题