【发布时间】:2017-08-29 21:10:33
【问题描述】:
在为对象编写单元测试时,我注意到当 CPU 上的负载很大时,pthread_cond_timedwait 不会很快超时。如果这些负载没有放在 CPU 上,一切正常。然而,当系统加载负载时,我发现无论我将超时设置为多少时间,真正的延迟都会关闭大约 50-100 毫秒。
例如,这里是程序单个时间间隔的打印输出,其中使用函数 GetTimeInMs 找到上次和当前时间。
// Printout, values are in ms
Last: 89799240
Current: 89799440
Period Length: 200
Expected Period: 100
从我读过的所有内容来看,这个问题通常是由使用相对时间而不是绝对时间引起的,但据我所知,我们正确使用了绝对时间。如果你们这些了不起的人能帮助我找出这里做错了什么,我将不胜感激。
这里展示了利用 timedwait 的函数。请注意,根据我所做的定时调试,我知道生成的额外时间是通过 timedwait 调用完成的,因此我没有包含其他不必要的代码。
bool func(unsigned long long int time = 100) // ms
{
struct timespec ts;
pthread_mutex_lock(&m_Mutex);
if (0 == m_CurrentCount)
{
// Current time + delay in ns
unsigned long long int absnanotime = (GetTimeInMs()+time)*1000000;
struct timespec ts;
ts.tv_nsec = absnanotime % 1000000000ULL;
ts.tv_sec = absnanotime / 1000000000ULL;
do
{
if (0 != pthread_cond_timedwait(&m_Condition, &m_Mutex, &ts))
{
// In the case I am testing, I hope to get here via timeout in 100 ms
pthread_mutex_unlock(&m_Mutex);
return false;
}
}
while (!m_CurrentCount);
}
pthread_mutex_unlock(&m_Mutex);
return true;
}
unsigned long long int GetTimeInMs()
{
unsigned long long int time;
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
time = ts.tv_nsec + ts.tv_sec * 1000000000ULL;
time = time / 1000000ULL; // Converts to ms
return time;
}
用于初始化func中使用的类变量的代码。
void init()
{
pthread_mutex_init(&m_Mutex, NULL);
pthread_condattr_init(&m_Attr);
pthread_condattr_setclock(&m_Attr, CLOCK_MONOTONIC);
pthread_cond_init(&m_Condition, &m_Attr);
}
模拟 CPU 负载的 CPU 吞噬线程正在运行以下 while 循环。
void cpuEatingThread()
{
while (false == m_ShutdownRequested);
{
// m_UselessFoo is of type float*
m_UselessFoo = new float(1.23423525);
delete m_UselessFoo;
}
}
【问题讨论】:
-
你从哪里读到它们满足实时要求(或者说 Linux 是一个 RTOS - 没有扩展)?
-
很抱歉,我不确定您在问什么。如果你问我从哪里得知应该对 pthread_cond_timedwait 使用绝对时间,我是从 Timed Wait Semantics 部分中的man page of the function itself 得到的。
-
维基百科应该有所帮助。
-
愿意提供您认为我应该在维基百科上阅读的内容吗?
-
很可能,当等待超时时,线程准备就绪,没有任何优先级提升或任何其他此类操作。如果盒子被加载,那么就绪线程可能不会立即运行。