经过5分钟后发生了一些事情,而其他代码仍在C ++中运行 [英] Make something happen after 5 minutes has passed, while other code still runs in C++
问题描述
我试图做一个计时器,所以五分钟后发生了一些事情.问题是,在不断检查计时器时,我需要其他代码才能运行.我在下面创建了一个示例,该示例显示了实际代码的外观,带有计时器的函数在类中,因此我在下面做了同样的事情.这是代码:
I am trying to make a timer, so after five minutes something happens. The catch is that while the timer is being checked constantly I need other code to be running. I have created a sample below, of how the actually code looks, the function with the timer is in class, so I did the same thing below. Here is the code:
此代码假定包含所有必需的标头
Class.h:
class MyClass
{
public:
void TimerFunc(int MSeconds);
};
void MyClass::TimerFunc(int MSeconds)
{
Sleep(MSeconds); //Windows.h
//Event code
return;
}
Main.cpp:
int main()
{
MyClass myClass;
myClass.TimerFunc(300); //300 is 5 minutes
//Here we do not want to wait for the five minutes to pass,
//instead we want to continue the rest of the code and check
//for user input as below
std::cout << "This should print before the Event Code happens.";
}
这里的问题是代码等待五分钟,然后继续.我不确定线程在这里是否会是一个好选择,我之前没有做太多事情,如果有人可以帮助我或者知道更好的解决方法,那么任何帮助都是值得的.
The problem here is that the code waits for the five minutes to pass, and then continues. I'm not sure if threading would be a good option here, I haven't done much with it before, if anyone could help me with that, or knows a better way to go about it, any help is appreciated.
推荐答案
对于C ++ 11线程,这将像这样工作:
With C++11 threads, this would work like this:
int main()
{
MyClass myClass;
thread ti([](MyClass &m){m.TimerFunc(300); }, ref(myClass)); // create and launch thread
// ... code executed concurrently to threaded code
ti.join(); // wait for the thread to end (or you'll crash !!)
}
将私人成员添加到您的班级:
Add a private member to your class:
atomic<bool> run=true; // designed to avoid race issue with concurrent access
将其计时器功能更新为在此变量为true时循环:
Update its timer function to loop while this variable is true:
void MyClass::TimerFunc(int MSeconds)
{
while (run) {
this_thread::sleep_for(chrono::milliseconds(MSeconds)); // standard sleep instead of microsoft's one
//Event code
}
return;
}
预见该类中的成员函数将停止线程循环:
Foresee within the class a member function to stop the threaded loop:
void Stop() {
run = false;
}
当不再需要计时器功能时(例如,在调用 ti.join()<之前),最后更新
main()
以调用 myClass.Stop()
/code>)
Finally update main()
to call myClass.Stop()
when the timer function is no longer needed (i.e. before calling ti.join()
)
注意,避免讨厌的错误:请小心在线程构造函数中引用 ref(myClass)
.如果您忘记了这一点,线程 ti
将使用对myClass副本的引用,而不是原始对象.
attention, nasty error to avoid: be careful to refer to ref(myClass)
in the thread constructor. If you would forget this, the thread ti
would use a reference to a copy of myClass instead of the original object.
这篇关于经过5分钟后发生了一些事情,而其他代码仍在C ++中运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!