关于C++临界区CriticalSection的问题。
我按照教程敲的代码,结果教程里面运行的没问题,而我运行时会崩溃。不是一开始就崩溃,有时是快结束了才崩溃,有时是中间就崩溃了。而且显示出来的都是线程二的,线程一都没有执行,...
我按照教程敲的代码,结果教程里面运行的没问题,而我运行时会崩溃。不是一开始就崩溃,有时是快结束了才崩溃,有时是中间就崩溃了。而且显示出来的都是线程二的,线程一都没有执行,这是怎么回事?求解。。。
下面是代码:
#include <windows.h>
#include <iostream.h>
DWORD WINAPI Run1proc(LPVOID lpParameter);
DWORD WINAPI Run2proc(LPVOID lpParameter);
int tickets=100;
CRITICAL_SECTION m_cs;
void main()
{
HANDLE hproc1;
HANDLE hproc2;
hproc1=CreateThread(NULL,0,Run1proc,NULL,0,NULL);
hproc2=CreateThread(NULL,0,Run2proc,NULL,0,NULL);
CloseHandle(hproc1);
CloseHandle(hproc2);
InitializeCriticalSection(&m_cs);
Sleep(5000);
DeleteCriticalSection(&m_cs);
}
DWORD WINAPI Run1proc(LPVOID lpParameter)
{
while (1)
{
EnterCriticalSection(&m_cs);
if (tickets>0)
{
Sleep(1);
cout<<"线程一运行:"<<tickets--<<endl;
}
else
break;
LeaveCriticalSection(&m_cs);
}
return 0;
}
DWORD WINAPI Run2proc(LPVOID lpParameter)
{
while (1)
{
EnterCriticalSection(&m_cs);
if (tickets>0)
{
Sleep(1);
cout<<"线程二运行:"<<tickets--<<endl;
}
else
break;
LeaveCriticalSection(&m_cs);
}
return 0;
} 展开
下面是代码:
#include <windows.h>
#include <iostream.h>
DWORD WINAPI Run1proc(LPVOID lpParameter);
DWORD WINAPI Run2proc(LPVOID lpParameter);
int tickets=100;
CRITICAL_SECTION m_cs;
void main()
{
HANDLE hproc1;
HANDLE hproc2;
hproc1=CreateThread(NULL,0,Run1proc,NULL,0,NULL);
hproc2=CreateThread(NULL,0,Run2proc,NULL,0,NULL);
CloseHandle(hproc1);
CloseHandle(hproc2);
InitializeCriticalSection(&m_cs);
Sleep(5000);
DeleteCriticalSection(&m_cs);
}
DWORD WINAPI Run1proc(LPVOID lpParameter)
{
while (1)
{
EnterCriticalSection(&m_cs);
if (tickets>0)
{
Sleep(1);
cout<<"线程一运行:"<<tickets--<<endl;
}
else
break;
LeaveCriticalSection(&m_cs);
}
return 0;
}
DWORD WINAPI Run2proc(LPVOID lpParameter)
{
while (1)
{
EnterCriticalSection(&m_cs);
if (tickets>0)
{
Sleep(1);
cout<<"线程二运行:"<<tickets--<<endl;
}
else
break;
LeaveCriticalSection(&m_cs);
}
return 0;
} 展开
2个回答
展开全部
----------------
HANDLE hproc1;
HANDLE hproc2;
hproc1=CreateThread(NULL,0,Run1proc,NULL,0,NULL);
hproc2=CreateThread(NULL,0,Run2proc,NULL,0,NULL);
CloseHandle(hproc1);
CloseHandle(hproc2);
InitializeCriticalSection(&m_cs);
Sleep(5000);
DeleteCriticalSection(&m_cs);
------------------------
把InitializeCriticalSection(&m_cs);移动到HANDLE hproc1;前面
HANDLE hproc1;
HANDLE hproc2;
hproc1=CreateThread(NULL,0,Run1proc,NULL,0,NULL);
hproc2=CreateThread(NULL,0,Run2proc,NULL,0,NULL);
CloseHandle(hproc1);
CloseHandle(hproc2);
InitializeCriticalSection(&m_cs);
Sleep(5000);
DeleteCriticalSection(&m_cs);
------------------------
把InitializeCriticalSection(&m_cs);移动到HANDLE hproc1;前面
更多追问追答
追问
这样好像是不崩溃,但我连续运行10遍了,全都是线程一再执行,线程二都没执行啊。这又是为什么呢?
追答
CloseHandle(hproc1);
把这两句注释掉
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询