确保两个线程同时启动

Ensure that two threads start at the same time

本文关键字:线程 启动 两个 确保      更新时间:2023-10-16

我有一个用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
    }
}

它并没有完全回答这个问题,但是这个变通方法对我来说很好。