简体   繁体   English

确保两个线程同时启动

[英]Ensure that two threads start at the same time

I have an application for which I code with Java and C++. 我有一个应用程序,我用Java和C ++编写代码。 In this application I need to have multiple "trials" that lasts exactly N seconds (let's say N = 15). 在这个应用程序中,我需要有多个“试验”,持续N秒(假设N = 15)。 What I also need is to log the current state every 0.005 seconds. 我还需要每隔0.005秒记录一次当前状态。 For this exact purpose I have the following code: 出于这个目的,我有以下代码:

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
    }
}

The thing is when I'm looking at my logging (which is then written in a file) I see that I get a different number of logging lines (thus meaning that one trial has logs till 14.5 seconds for instance and the other 14.3 and an other one 14.8). 问题是当我正在查看我的日志记录(然后将其写入文件中)时,我看到我获得了不同数量的日志记录行(因此意味着一个试验的日志记录为14.5秒,另一个则为14.3和另一个14.8)。 Is there any way to improve this code so as to get less differences between each trial. 有没有办法改进这个代码,以便减少每个试验之间的差异。

I think that the logging that I have to do in log() may be responsible for a small delay but honestly it is a really small logging (mainly adding things into a std::vector). 我认为我必须在log()执行的log()可能会导致一个小的延迟,但老实说,这是一个非常小的日志记录(主要是将内容添加到std :: vector中)。 Should I create an other parallel thread to do this logging as well so as not to waste time in my while loop in the log() function? 我是否应该创建另一个并行线程来执行此日志记录,以免在log()函数中浪费我的while循环时间?

I'm running short of ideas to improve this code so as to decrease the difference between each trial. 我缺乏改进此代码的想法,以减少每个试验之间的差异。 I hope my question is clear enough. 我希望我的问题很清楚。 If not feel free to comment to ask for further explanations. 如果没有随意发表评论请求进一步解释。

Thanks in advance, 提前致谢,

Turns out I have found a workaround that is doable without slowing the UI. 事实证明,我找到了一种可行的解决方法,而且不会降低UI的速度。 I just combined this two threads together in a single thread with a for loop 我只是将这两个线程组合在一个带有for循环的线程中

Final code looks like something like this. 最终代码看起来像这样。

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
    }
}

It does not entirely answer the question but the workaround works just fine for me. 它并没有完全回答这个问题,但解决方法对我来说效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM