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秒和几纳秒,它发现时间已经过去并且没有等待...如果有任何疑问,请告诉我.
小智 10
pthread_cond_timedwait使用绝对时间,因此需要:
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)