首先,資源讀取線程可以簡單設(shè)計為一個循環(huán)等待的線程結(jié)構(gòu),每隔一段時間檢查加載隊列中是否有內(nèi)容,如果有則進(jìn)行加載工作,如果沒有則繼續(xù)等待一段時間。這種方式雖然簡單清晰,但卻存在問題,如果等待時間設(shè)得過長,則加載會產(chǎn)生延遲,如果設(shè)得過短,則該線程被喚醒的次數(shù)過于頻繁,會耗費很多不必要的CPU時間。
然后,主線程是邏輯線程還是渲染線程?因為邏輯線程需要處理鍵盤鼠標(biāo)等輸入設(shè)備的消息,所以我起初將邏輯線程設(shè)為主線程,而渲染線程另外創(chuàng)建,但實際發(fā)現(xiàn),幀數(shù)很不正常,估計與WM_PAINT消息有關(guān),有待進(jìn)一步驗證。于是掉轉(zhuǎn)過來,幀數(shù)正常了,但帶來了一個新的問題,邏輯線程如何處理鍵盤鼠標(biāo)消息?
對于第一個問題,有兩種解決方案:
第一,我們可以創(chuàng)建一個Event,資源讀取線程使用WaitForSingleObject等待著個Event,當(dāng)渲染線程向加載隊列添加新的需加載的資源后,將這個Event設(shè)為Signal,將資源讀取線程喚醒,為了安全,我們?nèi)孕枰阡秩揪€程向加載隊列添加元素,以及資源加載線程從加載隊列讀取元素時對操作過程加鎖。
第二,使用在渲染線程調(diào)用PostThreadMessage,將資源加載的請求以消息的形式發(fā)送到資源價值線程,并在wParam中傳遞該資源對象的指針,資源加載線程調(diào)用WaitMessage進(jìn)行等待,收到消息后即被喚醒,這種解決方案完全不需要加鎖。
對于第二個問題,我們同樣可以用PostThreadMessage來解決,在主線程的WndProc中,將邏輯線程需要處理的消息發(fā)送出去,邏輯線程收到后進(jìn)行相關(guān)處理。
需要注意的是,我們必須搞清楚線程是在何時創(chuàng)建消息隊列的,微軟如是說:
The thread to which the message is posted must have created a message queue, or else the call to PostThreadMessage fails. Use one of the following methods to handle this situation.
- Call PostThreadMessage. If it fails, call the Sleep function and call PostThreadMessage again. Repeat until PostThreadMessage succeeds.
- Create an event object, then create the thread. Use the WaitForSingleObject function to wait for the event to be set to the signaled state before calling PostThreadMessage. In the thread to which the message will be posted, call PeekMessage as shown here to force the system to create the message queue.
PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE)
Set the event, to indicate that the thread is ready to receive posted messages.
看來,我們只需要在線程初始化時調(diào)一句PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE)就可以了,然后在主線程中如此這般:
switch ( uMsg )

{
case WM_PAINT:

{
hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:

{
m_pLogic->StopThread();
WaitForSingleObject( m_pLogic->GetThreadHandle(), INFINITE );
PostQuitMessage(0);
}
break;
default:

{
if ( IsLogicMsg( uMsg ) )

{
PostThreadMessage( m_pLogic->GetThreadID(), uMsg, wParam, lParam );
}
else

{
return DefWindowProc( hWnd, uMsg, wParam, lParam );
}
}
break;
}
在邏輯線程中這般如此:
MSG msg;
while ( m_bRunning )

{
if ( PeekMessage( &msg, NULL, 0, 0, PM_NOREMOVE ) )

{
if ( ! GetMessageW( &msg, NULL, 0, 0 ) )

{
return (int) msg.wParam;
}

MessageProc( msg.message, msg.wParam, msg.lParam );
}

LogicTick();
}
完成!

]]>