提升两个线程

boost two threads

本文关键字:两个 线程      更新时间:2023-10-16
关于循环的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。

究竟需要什么来制作它,这样我才能运行理论上不确定的线程?此外,我需要注意的内存泄漏方面的任何潜在问题都非常棒。

你知道join()是做什么的吗?当您调用它时,它会阻塞主线程,直到调用join的线程完成。在代码中,您启动一个线程,调用join等待它完成,然后启动另一个线程并重复此过程。调用detach()以允许执行继续(您不在乎线程何时完成执行(,或者在启动所有线程后调用join()(取决于您的需要(。

注意:只有当您希望等待线程完成执行时,才需要调用join。

一旦希望所有线程停止运行,就应该只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
}

为什么不转储所有的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();