【问题标题】:How to schedule simultaneously two functions at random intervals using itermerval and sigaction structures C++如何使用 itermerval 和 sigaction 结构 C++ 以随机间隔同时调度两个函数
【发布时间】:2012-08-05 14:52:59
【问题描述】:

这里是新代码sn-p:

#define SIMU_TIME 30
pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER ; 
pthread_cond_t condition = PTHREAD_COND_INITIALIZER ; 
void *timer(void *Ptr) 
{    while ((float) clock()/CLOCKS_PRE_TICKS < SIMU_TIME) 
       {  float mean = (float) Ptr ; 
         float interval = exponential(mean) ; 
         float goal = (float) clock()/CLOCKS_PRE_TICKS + interval ; 
         pthread_mutex_lock(&mutex) ;
         while(goal > (float) clock()/CLOCKS_PRE_TICKS ) ; 
        pthread_mutex_unlock(&mymutex) ; 
       }
return(NULL) ; 
}
void *AddPacket(void *Ptr) 
{
   pthread_cond_lock(&mymutex) ;
   pthread_cond_wait(&condition, &mymutex) ; 
     // do business
    pthread_unlock_mutex(&mymutex) ; 
   }
int main()
{  float mean = 1.5 ; 
  pthread_t thread1, thread2 ; 
  pthread_create(&thread1, NULL, &timer, (void *) mean) ; 
  pthread_create(&thread2, NULL, &AddPacket, NULL) ; 
  pthread_join(thread1, NULL) ; 
  pthread_join(thread2, NULL) ; 
  pthread_mutex_destroy(&mymutex) ; 
  pthread_cond_destroy(&condition) ;
  pthread_exit(NULL) ; 
}

由于 pthread_cond_wait 通常在一个线程在达到某个阈值之前不访问属性时使用,我们必须使用与此变量关联的互斥锁以避免任何竞争条件,但在我的情况下,两个线程不实际上不需要访问相同的内存区域,这只是在第一个线程允许时调度第二个线程的一种方式。在这种情况下,是否有必要在“pthread_cond_wait”之前调用“pthread_mutex_lock”?

【问题讨论】:

    标签: c++ scheduled-tasks handler setitimer


    【解决方案1】:

    问题是您可以同时拥有两个警报,或者同时拥有两个SIGALRM 处理程序。这可以通过多种方式解决。一种方法是使用事件队列。

    您还有另一个问题,就是您将信号处理程序设置为this。这有很多问题。首先是this 在函数中无效。原因是它是由内核直接调用的线程函数,因此没有有效的this。第二个是处理程序必须是一个函数,而不是一个类。请记住,信号处理程序是从操作系统调用的,它没有 C++ 类的概念。

    上述两个问题都可以通过实现某种event queue来解决。

    线程函数也有一个问题,当它们运行到最后时,线程也结束了。

    【讨论】:

    • 亲爱的 Joachim 先生,我知道拥有两个 SIGALARM 的事实可能会导致代码中出现重要的竞争问题,因为系统无法知道为每个信号调用哪个函数。我试图利用“pthread_cond_t”和“pthread_mutex_t”来解决这个问题。请在上面找到新代码 sn-p。如果我有你的意见,我将非常感激。谢谢
    • @user16841 在回答另一个问题时,我创建了一个简单的事件队列系统。我对它还不完全满意,但它确实有效。见stackoverflow.com/a/11866539/440558
    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 2021-02-08
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多