多線程編程可以提高程序的併發執行能力,那是不是線程越多越好呢?
大家可以參考下面的代碼做測試:
- #define MAX_WORKTHREAD 5
- map<int, int> m_task;//用於統計每個線程做的任務數
- std::deque<int> m_MsgQueue;//處理的消息隊列
- for (i=0; i<MAX_WORKTHREAD; i++)
- {
- int* nTemp = new int;
- *nTemp = i;
- hWTHandle[i] = CreateThread(NULL, 0, WorkThread, nTemp, 0, &g_dwWorkThread[i]);
- WorkThreadCout ++;
- m_task[i] = 0;
- Sleep(100);
- }
- DWORD WINAPI WorkThread(LPVOID lpParam)
- {
- // cout << "No." << g_dwThreadID << " thread is running." << endl;
- while (TRUE)
- {
- int* nRemp = (int*)lpParam;
- int n = -1;
- EnterCriticalSection(&g_cs);
- //cout << "No " << *nRemp << ", " << g_dwWorkThread[*nRemp] << " thread is running." << endl;
- LeaveCriticalSection(&g_cs);
- EnterCriticalSection(&g_MsgQueue);
- if (!m_MsgQueue.empty())
- {
- n = m_MsgQueue.front();
- m_MsgQueue.pop_front();
- m_task[*nRemp]++;
- }
- LeaveCriticalSection(&g_MsgQueue);
- EnterCriticalSection(&g_cs);
- cout << "No:" << *nRemp << ", " << n << endl;
- LeaveCriticalSection(&g_cs);
- Sleep(2000);//備註1
- }
- cout << "No " << lpParam << " end" << endl;
- return 0;
- }
當任務執行完了後,可以打印m_task裏的數據:
- std::map<int, int>::iterator IterCount;
- for(IterCount=m_task.begin(); IterCount!=m_task.end();IterCount++)
- {
- int nThreadId= (*IterCount).first;
- int nCount = (*IterCount).second;
- EnterCriticalSection(&g_cs);
- cout << "nThreadId:" << nThreadId << ", nCount" << nCount<<endl;
- LeaveCriticalSection(&g_cs);
- (*IterCount).second = 0;
- }
另外,多線程操作全局變量的時候,一定要用線程同步(如臨界區等)來操作,否則,會有問題。在使用的過程中,一定要注意資源和線程之間的關係,避免死鎖發生。
經過測試,多線程中的線程數是不是越多越好?這個問題的答案應該就有了。
原創鏈接:http://blog.csdn.net/wujunokay/article/details/12307773