确保两个线程同时启动
Ensure that two threads start at the same time
我有一个用Java和c++编写代码的应用程序。在这个应用程序中,我需要多次持续N秒的"试验"(假设N = 15)。我还需要每0.005秒记录一次当前状态。为了达到这个目的,我编写了以下代码:
std::thread timerTrial(&endTrial,this);
std::thread timerLog(&log,this);
std::thread timerTrial(&endTrial,this);
timerLog.detach();
timerTrial.detach();
void endTrial(){
usleep(TIME);
isOver = true ;
//...
}
void log(){
while(isOver == false){
usleep(TIMELOG);
//Do the logging
}
}
事情是当我看着我的日志记录(然后写在一个文件中),我看到我得到了不同数量的日志记录行(因此意味着一个试验的日志直到14.5秒,另一个14.3和另一个14.8)。有没有办法改进这个代码,使每次试验之间的差异更小?
我认为我必须在log()
中做的日志记录可能会导致小延迟,但老实说,这是一个非常小的日志记录(主要是将东西添加到std::vector中)。我是否应该创建另一个并行线程来做这个日志记录,以免在log()
函数的while
循环中浪费时间?
我缺乏改进这段代码的想法,以减少每次试验之间的差异。我希望我的问题足够清楚。如果没有,请随时评论并要求进一步解释。
提前致谢
我发现了一个可行的解决方案,而不会减慢UI。我只是用for
循环将这两个线程合并在一个线程中
最终代码看起来像这样:
std::thread timerTrial(&endTrial,this);
//....
void endTrial(){
int nbOfLogsNeeded = //Compute how many logs I will need during the time of trial
for(int i = 0 ; i < nbOfLogsNeeded ; i++){
std::this_thread::sleep_until(std::chrono::system_clock::now() + std::chrono::milliseconds(50));
//Perform Logging
}
}
它并没有完全回答这个问题,但是这个变通方法对我来说很好。
相关文章:
- 使用 std::string () const 函数启动线程或未来
- 如何创建线程序列以按照启动顺序执行任务?
- 启动类函数作为失去引用的线程
- 重新启动后,线程无法在 while 循环中再次运行
- 如何在C++上启动异步线程
- 计时器是否从另一个线程启动?
- 如何在 MFC 应用程序中启动 ZeroMQ 线程?
- C++ POCO - 如何在不使用 run() 方法的情况下启动线程池上的线程?
- 为什么 pthread_create() 返回 0 但线程从未启动
- 为什么 cuda-gdb 会启动多个线程?
- 对于每个线程,random_device是否以不同的状态启动?
- 线程启动延迟 - 通知所有未唤醒所有线程
- 等待多个线程启动,start() 未捕获
- Qt多线程启动线程错误
- 用信号通知线程启动特定的函数
- C++简单的线程启动问题
- - C++ - 使用计时器线程启动异常,精度毫秒
- 传递字符串作为线程启动例程参数:c++
- 错误:无法从另一个线程启动计时器.使用未声明计时器的QFuture
- QT线程:获取QObject::startTimer:计时器无法从另一个线程启动警告