std :: list线程push_back,front,pop_front [英] std::list threading push_back, front, pop_front
问题描述
std :: list线程安全吗?我假设它不是,所以我添加了自己的同步机制(我认为我有正确的说法).但是我仍然遇到问题
Is std::list thread safe? I'm assuming its not so I added my own synchronization mechanisms (I think i have the right term). But I am still running into problems
每个函数都由单独的线程调用. Thread1等不及了,它必须尽可能快
Each function is called by a separate thread. Thread1 can not wait, it has to be as fast as possible
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() ;
上遇到异常错误
After about 170k calls to thread1 and 900k calls to thread2 I get an exception error on CFoo& pFoo = g_buffer.front() ;
这将导致程序崩溃. stdthrow.cpp:22
That causes the program to crash. stdthrow.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
建议,评论,有没有更好的做事方法?
Suggestions, comments, is there a better way of doing things?
推荐答案
std :: list线程安全吗?
Is std::list thread safe?
当前的C ++标准甚至不承认线程的存在,因此std::list
当然不是.但是,不同的实现可能会提供(不同级别的)线程安全性.
The current C++ standard doesn't even acknowledge the existence of threads, so std::list
certainly isn't. Different implementations, however, might provide (different levels of) thread safety.
关于您的代码:如果需要锁,请使用锁.当在不同的内核上执行线程(从不同的缓存中获取变量)时,该bool
变量可能无济于事.请使用真实的互斥锁.
As for your code: If you need a lock, use a lock. That bool
variable might not help when the threads are executed on different cores which fetch it from different caches. Use a real mutex instead.
这篇关于std :: list线程push_back,front,pop_front的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!