多线程编程可以提高程序的并发执行能力,那是不是线程越多越好呢?
大家可以参考下面的代码做测试:
- #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