提升两个线程

时间:2013-02-16 22:52:59

标签: c++ multithreading boost boost-thread

C ++提出了关于循环的问题。

所以我一直在查看尽可能多的信息,但仍然没有看到我正在尝试做什么的例子或它的工作原理。

我在闲暇时间工作了几年,用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。

究竟需要什么才能使我能够运行理论上不确定线程​​的线程?在内存泄漏方面我需要注意的任何潜在问题都很难知道。

3 个答案:

答案 0 :(得分:1)

你知道join()的作用吗?当你调用它时,它会阻塞主线程,直到调用连接的线程完成。在你的代码中,你启动一个线程,调用join等到它完成,然后启动另一个线程并重复这个过程。调用detach()以允许执行继续(并且您不关心线程何时完成执行)或在启动所有线程后调用join()(根据您的需要)。

注意:您只想在等待线程完成执行时调用join。

答案 1 :(得分:0)

一旦您希望它们停止运行,您应该只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

}

答案 2 :(得分:0)

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