关于循环的C++ Boost问题。
因此,我一直在尽可能多地查看信息,但仍然没有看到任何关于我正在尝试做什么的例子或它的工作原理。
几年来,我一直在利用业余时间用C++设计一款游戏。我得到了我的游戏逻辑的核心引擎,以及一个粗略的输入系统,并使用OpenGL和AL作为输出。我想要做的是弄清楚如何让我的引擎启动,然后在单独的线程中运行我的输入系统、图形引擎和声音系统。并且全部同时运行。同步我的线程是下一步,但我不能让线程一起运行。
boost::thread gTrd(boost::bind(&game::runGraphics, this));
gTrd.join();
boost::thread sTrd(boost::bind(&game::runSound, this));
sTrd.join();
boost::thread iTrd(boost::bind(&game::runInput, this));
iTrd.join();
boost::thread cTrd(boost::bind(&game::runCore, this));
cTrd.join();这就是我到目前为止所得到的。问题是,据我所知,gTrd中的图形引擎有一个无限循环,它应该一直运行到程序终止,所以我打开了我的空白屏幕,但它从来没有启动过sTrd。
到底需要什么才能让我可以运行我的线程,理论上是不确定的线程?另外,我需要注意的内存泄漏方面的任何潜在问题都是很棒的。
发布于 2013-02-17 07:08:21
你知道join()是做什么的吗?当您调用它时,它会阻塞主线程,直到调用join的线程完成。在您的代码中,启动一个线程,调用join等待它完成,然后启动另一个线程并重复此过程。或者调用detach()以允许继续执行(并且您并不关心线程何时完成执行),或者在启动所有线程之后调用join() (取决于您的需要)。
注意:只有当您想要等待线程完成执行时才调用join。
发布于 2013-02-17 08:08:29
你应该只在你期望它们停止运行的时候join()所有的线程。正如您所说的,每个线程都在某种无穷无尽的循环中运行,所以当您在请求线程停止运行之前调用join()时,您的主线程将永远不会恢复其运行。
相反,您应该首先告诉线程您希望它们完成它们的运行。下面是一个用伪代码实现的简单机制,它可以做你想做的事情:
RunGame()
{
initialize_all_threads(); //just like your sample code does minus the join functions
...//do stuff while game is running
wait_for_quit_signal_from_input_thread(); //note that the input thread is the only thread which transfers messages back to the main thread
//quit signal received, so we should quit game
signal_all_threads_exit(); //via some kind of flag/synchronization object which all thread "main loops" are listening on
join_all_threads(); //wait for threads to gracefully end, perhaps with a timeout
}发布于 2013-02-17 15:45:34
为什么不直接丢弃所有的join()呢?
boost::thread gTrd(boost::bind(&game::runGraphics, this));
boost::thread sTrd(boost::bind(&game::runSound, this));
boost::thread iTrd(boost::bind(&game::runInput, this));
game::runCore();https://stackoverflow.com/questions/14916024
复制相似问题