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”?
尊敬的Joachim先生,我明白有两个SIGALARM会导致代码中的重要种族问题,因为系统无法知道每个信号需要调用哪个函数。我试图利用“pthread_cond_t”和“pthread_mutex_t”来解决问题。请在新的代码片段上面找到。如果我有你的意见,我会非常感激。谢谢 – Galileo 2012-08-06 10:21:36
@ user16841在回答另一个问题时,我创建了一个简单的事件队列系统。我还不完全满意,但它的工作原理。请参阅http://stackoverflow.com/a/11866539/440558 – 2012-08-08 14:27:35