问题描述
- 创建线程过多会出现线程不执行问题?
-
#include "stdafx.h"
#include
#include
#include
#include
using namespace std;DWORD CALLBACK ThreadFun_02(LPVOID lp);
bool PrintLog(const char * pString);
CRITICAL_SECTION g_Cs;
int g_iTickets = 20;
int main()
{
InitializeCriticalSection(&g_Cs);PrintLog("开始创建线程"); for(int i=0;i<g_iTickets;i++) { if(!CreateThread(NULL, 0, ThreadFun_02, NULL, 0, NULL)) { PrintLog("创建线程失败! "); } } cin.get(); cout<<g_iTickets<<endl; cin.get(); return 0;
}
DWORD CALLBACK ThreadFun_02(LPVOID lp)
{
EnterCriticalSection(&g_Cs);
if(g_iTickets > 0)
{
char szChar[20];
sprintf_s(szChar, "Sell ticket: %d", g_iTickets);
cout<<szChar<<endl;
PrintLog(szChar);
g_iTickets--;
}LeaveCriticalSection(&g_Cs); return 0;
}
bool PrintLog(const char * pString)
{
EnterCriticalSection(&g_Cs);
FILE *cLog = NULL;
cLog = fopen("Test.log", "a");if(!cLog) { return false; } fputs(pString, cLog); fputc(' ', cLog); fclose(cLog); LeaveCriticalSection(&g_Cs); return true;
}
代码如上,正常情况下最后输出的g_iTickets应该为0,但是如果g_iTickets过多(如50,100),就会出现最后的g_iTickets不为0的情况.这是什么情况呢?
g_iTickets=20情况下输出:
...
Sell ticket: 9
Sell ticket: 8
Sell ticket: 7
Sell ticket: 6
Sell ticket: 5
Sell ticket: 4
Sell ticket: 3
Sell ticket: 2
Sell ticket: 10
g_iTickets=50情况下输出:
...
Sell ticket: 9
Sell ticket: 8
Sell ticket: 7
Sell ticket: 6
Sell ticket: 5
Sell ticket: 4
Sell ticket: 3
Sell ticket: 21
g_iTickets=1000情况下输出:
Sell ticket: 45
Sell ticket: 44
Sell ticket: 43
Sell ticket: 42
Sell ticket: 41
Sell ticket: 40
Sell ticket: 39
Sell ticket: 38
Sell ticket: 3736
解决方案
linux环境下的线程的创建问题
C++创建线程问题 一段可用代码
MFC 线程创建的问题
解决方案二:
http://blog.csdn.net/chen825919148/article/details/7904219
解决方案三:
首先看你线程过多的时候,是否创建成功了这么多线程。
其次就是你的主线程有么有等待其他线程都执行完成,而不是主线程已经先退出了。