我想要队列安全的关键部分,以便线程不会同时访问队列。即使我评论与关键部分相关的行,此代码也有效。谁能解释为什么?
queue<int> que;
CRITICAL_SECTION csection;
int i=0;
DWORD WINAPI ProducerThread(void*)
{
while(1)
{
//if(TryEnterCriticalSection(&csection))
{
cout<<"Pushing value "<<i<<endl;
que.push(i++);
//LeaveCriticalSection(&csection);
}
}
}
//Consumer tHread that pops out the elements from front of queue
DWORD WINAPI ConsumerThread(void*)
{
while(1)
{
//if(TryEnterCriticalSection(&csection))
{
if(!que.empty())
{
cout<<"Value in queue is "<<que.front()<<endl;
que.pop();
}
else
Sleep(2000);
//LeaveCriticalSection(&csection);
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE handle[2];
//InitializeCriticalSection(&csection);
handle[0]=NULL;
handle[1]=NULL;
handle[0]=CreateThread(0,0,(LPTHREAD_START_ROUTINE)ProducerThread,0,0,0);
if(handle[0]==NULL)
ExitProcess(1);
handle[1]=CreateThread(0,0,(LPTHREAD_START_ROUTINE)ConsumerThread,0,0,0);
if(handle[1]==NULL)
ExitProcess(1);
WaitForMultipleObjects(2,handle,true,INFINITE);
return 0;
}