pthread_mutex 没有等待超时

pthread_mutex not waiting on timeout

我有以下代码:

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 毫秒。

知道我做错了什么吗?我只是重新发明轮子而不是使用 C++11 std::mutex 因为我需要为 IPC synchronisation/events 共享这个 Mutex(类似于 WinAPI 的 CreateEvent)。

pthread_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;
}