std :: list threading push_back,front,pop_front

Ste*_*rst 6 c++ multithreading stl

std :: list thread是安全的吗?我假设它不是这样我添加了自己的同步机制(我认为我有正确的术语).但我仍然遇到问题

每个函数都由一个单独的线程调用.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();
    }
}
Run Code Online (Sandbox Code Playgroud)

在大约170k调用thread1和900k调用thread2后,我得到一个异常错误 CFoo& pFoo = g_buffer.front() ;

这导致程序崩溃.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
Run Code Online (Sandbox Code Playgroud)

建议,评论,是否有更好的做事方式?

sbi*_*sbi 15

std :: list thread是安全的吗?

当前的C++标准甚至不承认线程的存在,所以std::list当然不是.然而,不同的实现可能提供(不同级别的)线程安全性.

至于你的代码:如果你需要锁,请使用锁.bool当线程在不同的核心上执行时,该变量可能没有帮助,这些核心从不同的缓存中获取它.请改用真正的互斥锁.


Meh*_*ari 6

不,它不保证是线程安全的.

您的同步机制存在缺陷.您正在使用它thread1时允许更改列表thread2.这可能会导致问题.除此之外,你应该使你的锁变量volatile.

  • @Steven:正如sbi在他的回答中所指出的,你最好使用系统提供的锁定机制,而不是自己动手. (3认同)