作者adrianshum (Alien)
看板C_and_CPP
标题Re: [问题] 加入thread之後, 变的相当缓慢
时间Thu Mar 26 10:49:06 2009
※ 引述《Mewra ()》之铭言:
: 有一个程式, 原本是希望能边让画面上的物件边走边听到语音,
: 但是以下的程式一执行起来, 整个画面跟几乎不能动一样, 物件行动的极其缓慢,
: 语音就更不用说了. 里面用了最简单的_beginthread(), 程式里的两个while是
: 必需的, 请问有办法改善吗? 谢谢
: bool repeat = true;
: void keyboard( void* parm )
: {
: mKeyboard->capture();
: if( mKeyboard->isKeyDown( A_DOWN ) )
: {
: .....
: }
: }
: void sound( void* parm )
: {
: while( repeat )
: {
: mRoot->checkIncomingMsg();
: }
: _endthread();
: }
: int main()
: {
: while( 1 )
: {
: _beginthread( keyboard, 0, NULL );
: _beginthread( sound, 0, NULL );
: }
: return 0;
: }
我猜你大概没有想清楚你在做什麽. :)
keyboard thread 只检查一次 keyboard, 要是 down 就做某东西, 然後就完了
sound thread 要是 repeat turn on 了的话就不断发声, 然後 invoke _endthread
main thread 不断地生成 keyboard 和 sound thread
每处做的都是很不寻常的东西
正常做法会是这样:
keyboard thread:
while (program running) {
check keyboard and do your work;
sleep for some time maybe;
}
sound thread:
while (program running) {
play your sound the way you want;
sleep for some time maybe;
}
main thread:
create keyboard thread
create sound thread;
// sleep?
wait for keyboard thread to end;
wait for sound thread to end;
不必无意义的疯狂生成 thread.
通常 threading library 有类似 join() 之类的方法
来 "等候 thread 完成"
你的 main thread 要是没有特别工作的, 不妨乾脆把
keyboard thread 做的东西放回到 main thread 做吧.
main thread 处理 keyboard input, 另生成一个 thread
做播放声音
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 202.155.236.82