2013-02-16 168 views
0

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。

究竟需要什么才能做到这一点,我可以运行我的线程理论上是无限的线程?另外,我需要关注内存泄漏的任何潜在问题都非常棒。

+0

似乎'runGraphics','runSound','runInput'等。应同时运行,但你正在等待各自与'。加入()'开始下一个之前完成。只有在启动所有线程后,才可能需要调用'.join()'。 – 2013-02-16 23:08:13

回答

1

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

注意:你只想在你想等到线程完成执行时调用加入。

+0

TY detach()声明可以工作,据我所知。仍然非常骨架的结构,并感谢您的功能差异的信息。 – 2013-02-17 01:52:32

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 

} 
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();