我想重做一个用Java做过的Conway生命游戏,但这次使用的是ncurses和C ++。显然我需要一个定时事件,所以我可以以可以查看的速率运行模拟。事实证明,在C ++中创建一个定时事件要比在Java中更难。我不像C ++那样有经验。我已经在网上看过了,我发现的东西让我看到了下面的代码。在执行时,它在终端中不产生任何结果。我究竟做错了什么?
main.cpp中:
Array(
[new_count] => 1
[updated_count] => 0
[error_count] => 0
[error_indices] => Array
(
)
[unmodified_indices] => Array
(
)
[persisted_recipients] => Array
(
[0] => ZEBhcy5jb20=
)
[errors] => Array
(
)
)
答案 0 :(得分:0)
您需要等待线程完成它正在做的事情,这通常是通过调用join()
来完成的。也许是这样的:
#include <iostream>
#include <functional>
#include <chrono>
#include <future>
#include <cstdio>
using namespace std;
class callBackTimer //no idea how this works, got it from Stack Overflow thread
{
public:
callBackTimer()
:_execute(false)
{}
void setup(int interval, std::function<void(void)> func)
{
_execute = true;
thread = std::thread([=]()
{
// while (_execute)
for (int steps = 0; steps < 100; ++steps)
{
func();
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
}
});
}
void stop()
{
_execute = false;
}
void run()
{
thread.join();
}
private:
bool _execute;
std::thread thread;
};
void timerExec()
{
cout << "SNAFU" << endl;
}
int main(int argc, const char * argv[])
{
callBackTimer timer; //declare the timer
std::function<void(void)> exec = timerExec; //declare a pointer to timerExec
timer.setup(25, std::bind(exec)); //start the timer
timer.run();
return 0;
}
调用detach()
即可,但您必须让main()
手动等待该线程。您还需要一个条件来突破while
循环,否则它将永远持续下去。希望有所帮助!