那么pthread_cond_timedwait()

Cip*_*er0 7 c pthreads

void wait(int timeInMs)
{
    struct timespec timeToWait;
    timeToWait.tv_sec = 5;
    timeToWait.tv_nsec = timeInMs*1000;

    int rt;

    pthread_mutex_lock(&fakeMutex);
    rt = pthread_cond_timedwait(&fakeCond, &fakeMutex, &timeToWait);
    pthread_mutex_unlock(&fakeMutex);
}
Run Code Online (Sandbox Code Playgroud)

我正在使用此代码尝试让一个线程等待一下,但它根本不起作用.没有错误,它只是不会使程序执行得更慢.

我想也许每个线程都需要拥有它自己的条件和互斥量,但这对我来说真的没有意义.

小智 17

使用任何睡眠变体,都不能保证行为.由于内核不知道不同的线程,所有线程也可以休眠.

使用更安全,更清洁的解决方案pthread_cond_timedwait.您错误地使用了API.这是一个更好的例子:

pthread_mutex_t fakeMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t fakeCond = PTHREAD_COND_INITIALIZER;

void mywait(int timeInMs)
{
    struct timespec timeToWait;
    struct timeval now;
    int rt;

    gettimeofday(&now,NULL);


    timeToWait.tv_sec = now.tv_sec+5;
    timeToWait.tv_nsec = (now.tv_usec+1000UL*timeInMs)*1000UL;

    pthread_mutex_lock(&fakeMutex);
    rt = pthread_cond_timedwait(&fakeCond, &fakeMutex, &timeToWait);
    pthread_mutex_unlock(&fakeMutex);
    printf("\nDone\n");
}

void* fun(void* arg)
{
    printf("\nIn thread\n");
    mywait(1000);
}

int main()
{
    pthread_t thread;
    void *ret;

    pthread_create(&thread, NULL, fun, NULL);
    pthread_join(thread,&ret);
}
Run Code Online (Sandbox Code Playgroud)

您需要指定从当前时间等待的时间.因为你只告诉5秒和几纳秒,它发现时间已经过去并且没有等待...如果有任何疑问,请告诉我.

  • 对我来说,gettimeofday(&now,NULL)不起作用,但这样做(200ms):clock_gettime(CLOCK_REALTIME,&timeToWait); timeToWait.tv_nsec + = 200000000UL; timeToWait.tv_nsec%= 1000000000UL; timeToWait.tv_sec + = timeToWait.tv_nsec <200000000UL?1:0; (2认同)

Dav*_*rtz 14

pthread_cond_timedwait函数需要绝对时间,而不是相对时间.它需要你想要停止等待的时间,而不是你想等多久.


小智 10

pthread_cond_timedwait使用绝对时间,因此需要:

  • 使用gettimeofday来检索当前时间.
  • timespec.tv_nsec是纳秒,它不能大于1秒.
  • timeval.tv_usec是微秒(1000纳秒).
  • timeInMs是毫秒:1毫秒= 1000微秒= 1000*1000纳秒.

    void wait(int timeInMs)
    {
        struct timeval tv;
        struct timespec ts;
    
        gettimeofday(&tv, NULL);
        ts.tv_sec = time(NULL) + timeInMs / 1000;
        ts.tv_nsec = tv.tv_usec * 1000 + 1000 * 1000 * (timeInMs % 1000);
        ts.tv_sec += ts.tv_nsec / (1000 * 1000 * 1000);
        ts.tv_nsec %= (1000 * 1000 * 1000);
    
        int n = pthread_cond_timedwait(&condition, &mutex, &ts);
        if (n == 0)
            // TODO: singaled
        else if (n == ETIMEDOUT)
            // TODO: Time out.
    }
    
    Run Code Online (Sandbox Code Playgroud)


Ark*_*nez 2

该代码不会休眠,它会检查条件一段时间。由于您可能没有设置 cond ok,它会立即返回。

如果您不愿意围绕信号同步线程,那么 pthread_cond _wait 就不是您所需要的。请在此处查看条件变量的工作原理。

如果你想以秒为单位精确睡眠,请使用sleep

如果您想以微秒精度睡眠,请使用select with timevals。

  • 使用带有 timeval 和 NULL 的“select”作为读、写、异常参数。请注意,使用这种方式选择仅适用于Linux,在Windows中,如果仅提供timeval参数,则选择立即返回 (3认同)