0

次のコードがあります。

bool Mutex::timed_lock(unsigned long milliseconds)
{
    if (!milliseconds)
    {
        return lock();
    }

    struct timespec ts;
    ts.tv_sec = milliseconds / 1000;
    ts.tv_nsec = (milliseconds - (ts.tv_sec * 1000)) * 1000000;

    //printf("%lld, %ld\n\n", ts.tv_sec, ts.tv_nsec);


    int res = pthread_mutex_timedlock(&info->mutex, &ts);
    info->ref_count += res != ETIMEDOUT && res != EDEADLK && !res ? 1 : 0;
    return res != ETIMEDOUT && res != EDEADLK && !res;
}

次に、次のようにテストしてみました。

Mutex lock;

std::thread([&]{
    std::cout<<"LOCKED: "<<std::boolalpha<<lock.lock()<<"\n";
    Sleep(5000);
}).detach();
Sleep(1000);

std::cout<<"DONE: "<<std::boolalpha<<lock.timed_lock(6600)<<"\n";

その結果、「LOCKED: true \n DONE: false」と出力ETIMEDOUTされ、エラーになります。ロックできない場合、6600 ミリ秒の間ブロックすることになっています。

私が間違っていることはありますか?std::mutexこのミューテックスは IPC 同期/イベント (WinAPIのCreateEvent.

4

1 に答える 1

3

タイムアウト topthread_mutex_timedlock()は絶対タイムアウトであり、相対タイムアウトではありません。したがって、現在の時間を把握し、将来の絶対時間を計算する必要があります。

struct timespec ts;
struct timespec now;
gettimeofday(&now, NULL);
ts->tv_sec = now.tv_sec + milliseconds/1000;
ts->tv_nsec = (now.tv_usec * 1000) + ((milliseconds%1000) * 1000000);
if (ts.tv_nsec >= 1000000000) {
     ts.tv_sec++;
     ts.tv_nsec -= 1000000000;
}
于 2015-02-16T08:43:20.377 に答える