【发布时间】:2013-01-28 13:19:00
【问题描述】:
我想要队列安全的关键部分,以便线程不会同时访问队列。即使我评论与关键部分相关的行,此代码也有效。 谁能解释一下为什么?
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;
}
【问题讨论】:
-
定义“作品”。 AFAICS 进程在启动第一个线程后立即退出。
-
@R.MartinhoFernandes 尽管没有缩进,
ExitProcess调用是有条件的,只在错误情况下运行 -
@simonc 哦,你是对的。孩子们,这就是为什么你应该正确缩进你的代码。
-
您有多核处理器(或多个处理器)吗?您运行了多长时间,您是否尝试过不使用“cout”[只需检查您现在获得的值+1 是否等于您下一次获得的值]。
标签: c++ multithreading winapi thread-safety