我有一个有两个线程的进程,它是这样工作的
Thread1
while( true ){
Time t = getTime();
Notify/wakeup Thread2 after time 't'
....
....
}Thread2
while( true ) {
wait for a signal from Thread1
do some stuff
}有没有办法实现这个场景?
PS:我正在使用Pthread库,也准备使用其他库了。
谢谢
发布于 2012-03-02 18:28:11
使用usleep、条件变量和状态变量的组合:
pthread_cond_t cond;
pthread_mutex_t mutex;
int state = 0;
clock_t start, stop;
while( true ){
Time t = getTime();
start = clock();
// do some action
stop = clock();
if((stop - start) < t)
usleep(t - (stop - start));
pthread_mutex_lock(&mutex)
state++;
pthread_cond_signal(&cond);
pthread_mutex_unlock(mutex);
}然后在线程2中:
while( true ) {
pthread_mutex_lock(&mutex);
int st = state;
while(state == st)
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
do some stuff
}https://stackoverflow.com/questions/9528762
复制相似问题