pthread_cond_timedwait() [英] pthread_cond_timedwait()

查看:89
本文介绍了pthread_cond_timedwait()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我正在使用此代码尝试让线程等待一段时间,但它根本不起作用.没有错误,只是不会使程序执行速度变慢.

I'm using this code to try to get a thread to wait around for a bit, but it doesn't work at all. No errors, it just doesn't make the program execute any slower.

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

I was thinking maybe each thread needs to have it's own condition and mutex, but that really doesn't make sense to me.

推荐答案

使用 sleep 的任何变体,都无法保证行为.所有线程也可以休眠,因为内核不知道不同的线程.

Using any variant of sleep, the behavior is not guaranteed. All the threads can also sleep since the kernel is not aware of the different threads.

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

A safer and cleaner solution to use is pthread_cond_timedwait. You used the API incorrectly. Here is a better example:

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

您需要指定从当前时间开始等待的时间.由于你只告诉了 5 秒和一些纳秒,它发现时间已经过去了,没有等待......如果还有疑问,请告诉我.

You need to specify how much time to wait from current time. Since you were only telling 5 sec and some nano-seconds it found that the time had already passed and did not wait...Please let me know if any more doubts.

这篇关于pthread_cond_timedwait()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆