sem_timedwait与CLOCK_MONOTONIC_RAW / CLOCK_MONOTONIC

时间:2016-11-19 22:07:28

标签: c++ c linux linux-kernel

genre.id的示例代码使用int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);作为CLOCK_REALTIME的时间源,但这很容易受系统时钟时间的影响,例如某些其他进程更改时间。

是否支持clock_gettime(struct timespec *timeout)支持sem_timedwait时间来源

下面是一些示例代码供参考。

CLOCK_MONOTONIC

3 个答案:

答案 0 :(得分:4)

  

是否支持sem_timedwait以支持CLOCK_MONOTONIC时间源

简短回答:no

但如果您不使用第三方库或C ++ 11并且不需要跨平台兼容性,那么您可以实施一个:

#include <cstring> // memset
#include <ctime>   // DEV_NOTE: some systems might need -lrt
#include <csignal> // DEV_NOTE: csignal contains a reference to CLOCK_MONOTONIC
#include <semaphore.h>
#if !defined(CLOCK_MONOTONIC)
    #error CLOCK_MONOTONIC is not defined
#endif

typedef struct timespec tick_t;

static tick_t monotonic_tick()
{
    tick_t tmp;
    if (clock_gettime(CLOCK_MONOTONIC, &tmp) != 0) {
        std::memset(&tmp, 0, sizeof(tick_t));
        // error, throw std::exception(std::strerror(errno))
    }
    return tmp;
}

static double elapsed_us(tick_t init, tick_t end)
{
    return ((end.tv_sec - init.tv_sec) * 1000000) + (static_cast<double>((end.tv_nsec - init.tv_nsec)) / 1000);
}

static double elapsed_ms(tick_t init)
{
    return (elapsed_us(init, monotonic_tick()) / 1000);
}

static int sem_timed_wait(sem_t& sem, unsigned long timeout_ms)
{
    if (timeout_ms == 0) {
        if (sem_trywait(&sem) == 0) {
            return 0;
        }
    } else {
        tick_t start = monotonic_tick();
        do {
            if (sem_trywait(&sem) == 0) {
                return 0;
            }
        } while (elapsed_ms(start) <= timeout_ms);
    }
    return -1;
}

然后使用它:

#include <iostream>
#include <pthread.h>

void* thread_fn(void* val)
{
    sem_t* sem = static_cast<sem_t*>(val);
    std::cout << std::endl << pthread_self() << " thread started" << std::endl;

    if (sem_timed_wait(*sem, 1000) == 0) {
        std::cout << std::endl << pthread_self() << " got it, sleeping 2 seconds..." << std::endl;
        sleep(2); // sleep 2 seconds
        std::cout << pthread_self() << " returning..." << std::endl;
        // don't forget to release since we acquired the lock
        sem_post(sem);
    } else {
        std::cout << pthread_self() << " timeout" << std::endl;
    }
    std::cout << pthread_self() << " thread returning" << std::endl;
    return NULL;
}

int main(int argc, char* argv[])
{
    sem_t sem;
    pthread_t t1, t2;
    sem_init(&sem, 0, 1); // binary semaphore

    std::cout << "Creating..." << std::endl;
    pthread_create(&t1, NULL, thread_fn, static_cast<void*>(&sem));
    pthread_create(&t2, NULL, thread_fn, static_cast<void*>(&sem));

    std::cout << "Joining..." << std::endl;
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    std::cout << "Leaving..." << std::endl;
    return 0;
}

以上工作适用于各种* nix系统,包括BSD系列。如果您需要跨平台的方式来执行此操作,Windows和Apple可以使用更简单的机制来执行此操作。

希望可以提供帮助。

答案 1 :(得分:3)

POSIX系统遇到相同的问题, 基于C++0x has no semaphores? How to synchronize threads?How do I deal with the system clock changing while waiting on a std::condition_variable?和HalûkUçar的答案

#include <stdio.h>
#include <thread>            
#include <time.h>
#include <unistd.h>
#include <pthread.h>
class semaphore
{
private:   
   pthread_mutex_t m_mutex = PTHREAD_MUTEX_INITIALIZER;
   pthread_condattr_t m_attr;
   pthread_cond_t m_cond;

   unsigned long count_ = 0;   

   public :
   void init_sem()
   {
      int result = 0;
      result = pthread_condattr_init(&m_attr);

      result = pthread_condattr_setclock(&m_attr, CLOCK_MONOTONIC);

      result = pthread_cond_init(&m_cond, &m_attr); 
   }

   void notify() {
      pthread_mutex_lock(&m_mutex);
      ++count_;
      pthread_cond_signal(&m_cond);
      pthread_mutex_unlock(&m_mutex);
   }



   void wait() {
      pthread_mutex_lock(&m_mutex);
      while (!count_) // Handle spurious wake-ups.
      {
        pthread_cond_wait(&m_cond, &m_mutex);
      }
      --count_;
      pthread_mutex_unlock(&m_mutex);

   }

   void wait_for(int sec)
   {
      int rc = 0;
      pthread_mutex_lock(&m_mutex);
      if (!count_)
      {
         timespec tsTimeout;
         clock_gettime(CLOCK_MONOTONIC, &tsTimeout);

         // update time calculation to your specific case
         tsTimeout.tv_sec += time;

         // Handle spurious wake-ups.
         while (!count_ && (rc == 0))
         {
            rc = pthread_cond_timedwait(&m_cond, &m_mutex, &tsTimeout);
         }

      }

      if (rc == 0)
      {        
         printf("success\n");

         --count_;
      }
      else if (rc == ETIMEDOUT)
      {
         printf("timeout\n");
      }
      else
      {
         printf("error\n");
      }

      pthread_mutex_unlock(&m_mutex);
   }      

   bool destroy()
   {
      return ((pthread_cond_destroy(&m_cond) == 0)
        && (pthread_mutex_destroy(&m_mutex) == 0)
        && (pthread_condattr_destroy(&m_attr)==0)) ? true : false;
   }
};

答案 2 :(得分:1)

您可以通过使用

来实现自己的信号量例程
  • 用于sem_post()的pthread_cond_signal()
  • 用于sem_timedwait()的pthread_cond_timedwait()
  • 用于sem_wait()的pthread_cond_wait()
  • 当前时间为sem_trywait()的pthread_cond_timedwait()

当然,信号量的创建和删除将包括malloc和free,您可以在其中分配具有信号量实现所需的所有参数(mutex,condition等)的结构。