2012-03-02 104 views
0

我有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庫,準備使用其他庫也。

由於

+0

如果的getTime()自1970年以來返回毫秒, 't時間過後'是什麼意思? '有些情況'阻止嗎? – 2012-03-02 08:32:38

+0

'getTime()'返回絕對時間(可能是毫秒或秒)不是相對於某個特定年份 – 2012-03-02 09:43:30

+0

我已經移除了'某些條件'以避免混淆。 – 2012-03-02 09:46:06

回答

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 
} 
+0

這可能是一種解決方法,但我不想讓Thread1進入睡眠狀態,因爲它有一些其他的事情要做。 – 2012-03-02 10:38:55

+0

所以你想要的東西是這樣的:thread1啓動,做了一些動作,但是如果在動作結束時沒有經過t毫秒,等到t已經過去,然後發信號給thread2吧?檢查我所做的編輯是否正確。 – Tudor 2012-03-02 10:40:35

+0

@David Schwartz:謝謝。 – Tudor 2012-03-02 16:18:00