#include <sys/time.h>
#include <pthread.h>
#include <cstdio>
#include <iostream>
timespec m_timeToWait;
pthread_mutex_t m_lock;
pthread_cond_t m_cond;
timespec & calculateNextCheckTime(int intervalSeconds){
timeval now{};
gettimeofday(&now, nullptr);
m_timeToWait.tv_sec = now.tv_sec + intervalSeconds;
//m_timeToWait.tv_nsec = (1000 * now.tv_usec) + intervalSeconds;
return m_timeToWait;
}
void *run(void *){
int i = 0;
pthread_mutex_lock(&m_lock);
while (i < 10) {
std::cout << "Waiting .." << std::endl;
int ret = pthread_cond_timedwait(&m_cond, &m_lock, &calculateNextCheckTime(1));
std::cout << "doing work" << std::endl;
i++;
}
pthread_mutex_unlock(&m_lock);
}
int main()
{
pthread_t thread;
int ret;
int i;
std::cout << "In main: creating thread" << std::endl;
ret = pthread_create(&thread, NULL, &run, NULL);
pthread_join(reinterpret_cast<pthread_t>(&thread), reinterpret_cast<void **>(ret));
return 0;
}
在SO上也有类似的例子,但我似乎无法弄清楚。而且,Clion IDE坚持要求我在pthread_join参数上使用重新解释强制类型转换,即使SO上的示例没有适当的强制类型转换。我正在使用C ++ 11。
答案 0 :(得分:0)
这只是数学。
您可以访问tv_sec
,也可以访问tv_nsec
。
tv_sec
设置为“ 现在的秒部分,加上 X 秒”。tv_nsec
设置为“ now 的纳秒部分,再加上 Y 纳秒”。结果为“现在,加上 X 秒和 Y 纳秒”……这是您希望程序(最早)以纳秒分辨率等待的时间。
只需取消注释执行此操作的行,然后为您要执行的操作提供适当的数字即可。
您可以让函数接受一个额外的“毫秒”参数(不要忘记将其乘以1,000,000!),然后根据需要将“秒”保留为零:
timespec& calculateNextCheckTime(const int intervalSeconds, const int intervalMillis)
{
timeval now{};
gettimeofday(&now, nullptr);
m_timeToWait.tv_sec = now.tv_sec + intervalSeconds;
m_timeToWait.tv_nsec = (1000 * now.tv_usec) + (1000 * 1000 * intervalMillis);
return m_timeToWait;
}
您可能希望或不希望进行一些范围检查(即验证intervalMillis >= 0 && intervalMillis < 1000
),以避免造成严重的溢出。
或者,相反,您可能希望允许将calculateNextCheckTime(1, 234)
与calculateNextCheckTime(3, 34)
相同。这将起作用,但这只是因为您还需要实现“进位”语义,以确保在添加m_timeToWait.tv_nsec
组件之后(1000 * now.tv_usec)
小于1,000,000,000,主叫用户没有该组件控制。 (在上面的示例中,我还没有实现。)
此外,您可能希望也可能不希望使用这些参数unsigned
。