2013-02-16 163 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();