2012-08-05 29 views
0

在这里,新的代码片断:如何安排在随机的时间间隔使用itermerval同时两个函数和sigaction的结构C++

#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通常用于当一个线程不访问的attribut一定的门槛,我们必须使用一个与此变量相关的互斥体来避免任何竞争条件,但在我的情况下,这两个线程实际上并不需要访问相同的内存区域,这只是一种安排第二个线程时的方式第一个允许它。在这种情况下,有必要在“pthread_cond_wait”之前调用“pthread_mutex_lock”?

回答

0

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

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

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

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

+0

尊敬的Joachim先生,我明白有两个SIGALARM会导致代码中的重要种族问题,因为系统无法知道每个信号需要调用哪个函数。我试图利用“pthread_cond_t”和“pthread_mutex_t”来解决问题。请在新的代码片段上面找到。如果我有你的意见,我会非常感激。谢谢 – Galileo 2012-08-06 10:21:36

+0

@ user16841在回答另一个问题时,我创建了一个简单的事件队列系统。我还不完全满意,但它的工作原理。请参阅http://stackoverflow.com/a/11866539/440558 – 2012-08-08 14:27:35

相关问题