线程同步

时间:2012-03-02 06:04:12

标签: multithreading pthreads

我有一个2线程的进程,就像这样工作

线程1

while( true ){
    Time t = getTime();
    Notify/wakeup Thread2 after time 't'

    ....
    ....
}

线程2

while( true ) {
     wait for a signal from Thread1

     do some stuff 
}

有没有办法实现这种情况?

如果getTime()返回5个单位(绝对时间)的时间,那么Thread2应该在5个单位时间后开始执行。

PS:我正在使用Pthread库,也准备使用其他库。

谢谢

1 个答案:

答案 0 :(得分:0)

使用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 
}
相关问题