2013-11-09 28 views
0

我嘗試使用pthread實現以下邏輯(一種僞代碼):並行線程:鎖定互斥與超時

pthread_mutex_t mutex; 

threadA() 
{ 
    lock(mutex); 
    // do work 
    timed_lock(mutex, current_abs_time + 1 minute); 
} 

threadB() 
{ 
    // do work in more than 1 minute 
    unlock(mutex); 
} 

我確實希望threadA做的工作,然後等待直到threadB信號,但不長於1分鐘。我在Win32中做了類似的很多時間,但是仍然使用pthreads:timed_lock部分立即返回(不在1分鐘內),代碼爲ETIMEDOUT

有沒有簡單的方法來實現上述邏輯?

即使下面的代碼返回ETIMEDOUT立即

pthread_mutex_t m; 
// Thread A 
pthread_mutex_init(&m, 0); 
pthread_mutex_lock(&m); 
// Thread B 
struct timespec now; 
clock_gettime(CLOCK_MONOTONIC, &now); 
struct timespec time = {now.tv_sec + 5, now.tv_nsec}; 
pthread_mutex_timedlock(&m, &time); // immediately return ETIMEDOUT 

有誰知道爲什麼嗎?我也試圖與gettimeofday功能

感謝

+0

這裏的邏輯很奇怪,你的threadA鎖定了兩次互斥鎖。然而,最大的問題是你的threadA鎖定了互斥鎖,而threadB解鎖了它。你不能用pthread_mutex做到這一點,你必須在鎖定它的同一個線程中解鎖一個互斥鎖。 – nos

+0

你可能想要更像'pthread_cond_timedwait'的東西,但不清楚你真的在做什麼,因爲如上所述。 – Duck

+0

我真的很想實現像Windows事件。是的,鴨子,我用條件變量來完成它。一切正常 – andrii

回答

1

我實現了我的條件變量的邏輯相對於其他規則(使用包裝互斥,布爾標誌等) 謝謝大家徵求意見。

0

嘗試這樣的事:

class CmyClass 
{ 
    boost::mutex mtxEventWait; 
    bool WaitForEvent(long milliseconds); 
    boost::condition cndSignalEvent; 
}; 

bool CmyClass::WaitForEvent(long milliseconds) 
{ 
    boost::mutex::scoped_lock mtxWaitLock(mtxEventWait); 
    boost::posix_time::time_duration wait_duration = boost::posix_time::milliseconds(milliseconds); 
    boost::system_time const timeout=boost::get_system_time()+wait_duration; 
    return cndSignalEvent.timed_wait(mtxEventWait,timeout); // wait until signal Event 
} 

//所以序等待隨後致電WaitForEvent方法

WaitForEvent(1000); // it will timeout after 1 second 

//這是一個事件怎麼能夠發信號:

cndSignalEvent.notify_one();