【发布时间】:2010-12-23 01:10:00
【问题描述】:
std::list 线程安全吗?我假设它不是,所以我添加了我自己的同步机制(我认为我有正确的术语)。但我仍然遇到问题
每个函数都由一个单独的线程调用。 Thread1 等不及了,它必须尽可能快
std::list<CFoo> g_buffer;
bool g_buffer_lock;
void thread1( CFoo frame ) {
g_buffer_lock = true ;
g_buffer.push_back( frame ) ;
g_buffer_lock = false;
}
void thread2( )
{
while( g_buffer_lock ) {
// Wait
}
// CMSTP_Send_Frame * pMSTPFrame = NULL ;
while ( ! g_buffer_lock && g_buffer.size() > 0 )
{
// Get the top item
CFoo& pFoo = g_buffer.front() ;
// Do something.
// remove the front item
g_buffer.pop_front();
}
}
在大约 170k 次线程 1 调用和 900k 次线程 2 调用后,CFoo& pFoo = g_buffer.front() ; 出现异常错误
这会导致程序崩溃。标准抛出.cpp: 22
#ifdef _DEBUG
_CRTIMP2_PURE void __CLRCALL_PURE_OR_CDECL _Debug_message(const wchar_t *message, const wchar_t *file, unsigned int line)
{ // report error and die
if(::_CrtDbgReportW(_CRT_ASSERT, file, line, NULL, message)==1)
{
::_CrtDbgBreak();
}
}
_CRTIMP2_PURE void __CLRCALL_PURE_OR_CDECL _Debug_message(const unsigned short *message, const unsigned short *file, unsigned int line)
{ // report error and die
_Debug_message((wchar_t *) message, (wchar_t *) file, line);
}
#endif
建议,cmets,有没有更好的做事方式?
【问题讨论】:
-
std::list 线程安全吗?没有。
标签: c++ stl multithreading