C++可阻断式休眠

class BlockableSleep {
  public:
    /**
     * @brief 开始休眠
     * @ param [in] msec: 休眠时间/毫秒
     */
    void Sleep(const long& msec) {
        struct timeval now;
        struct timespec outtime;
        gettimeofday(&now, NULL);
        outtime.tv_sec = now.tv_sec + msec / 1000;
        outtime.tv_nsec = (now.tv_usec + msec % 1000) * 1000;

        pthread_mutex_lock(&m_mutex);
        pthread_cond_timedwait(&m_cond, &m_mutex, &outtime);
        pthread_mutex_unlock(&m_mutex);
    }

    /// @brief 唤醒线程
    void Wakeup() {
        pthread_mutex_lock(&m_mutex);
        pthread_cond_signal(&m_cond);
        pthread_mutex_unlock(&m_mutex);
    }
    virtual ~BlockableSleep() {
        pthread_mutex_destroy(&m_mutex);
        pthread_cond_destroy(&m_cond);
    }
  private:
    pthread_mutex_t m_mutex = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t m_cond = PTHREAD_COND_INITIALIZER;
};

你可能感兴趣的:(c++,sleep)