简体   繁体   English

在多线程环境中使用CList

[英]Using CList in a multithreaded environment

I am using a CList in a multithreaded environment and I keep having problem with the GetHead method. 我在多线程环境中使用CList,但GetHead方法始终有问题。 I have one thread that add data to the list, and an other thread who read and remove data from the list. 我有一个线程将数据添加到列表中,另一个线程从列表中读取和删除数据。 Here is the reading part : 这是阅读部分:

 value_type get_next()  
        {
          T t;
          if(!queue.IsEmpty()) {
             t = queue.GetHead();
          }
          return t;  //If the queue is empty we return an empty element
        }

Here is the inserting part : 这是插入部分:

 inline void insert(T &_in) 
        {
          queue.AddTail(_in);
        } 

Here is the removing part 这是去除部分

  inline void  pop_next()  
        {
          if(!queue.IsEmpty())  {
            queue.RemoveHead(); 
          }
        }

Why do I get a runtime error when I run this. 为什么运行此命令时会出现运行时错误。 It always fail at 它总是在失败

t = queue.GetHead();

With this assertion : 有了这个断言:

template<class TYPE, class ARG_TYPE>
AFX_INLINE TYPE& CList<TYPE, ARG_TYPE>::GetHead()
    { ENSURE(m_pNodeHead != NULL);
        return m_pNodeHead->data; }

While the m_pNodeHead value is : 虽然m_pNodeHead的值为:

  • pNext 0x00000000 {pNext=??? pNext 0x00000000 {pNext = ??? pPrev=??? pPrev = ??? data={...} } CList > >,ATL::CStringT > > &>::CNode * data = {...}} CList>> ,, ATL :: CStringT>>&> :: CNode *
  • pPrev 0x00000000 {pNext=??? pPrev 0x00000000 {pNext = ??? pPrev=??? pPrev = ??? data={...} } CList > >,ATL::CStringT > > &>::CNode * data = {...}} CList>> ,, ATL :: CStringT>>&> :: CNode *
  • data "" TESTSETSE ATL::CStringT > > 数据“” TESTSETSE ATL :: CStringT>>

You have a race condition between inserting and retrieving the value. 您在插入和检索值之间有一个竞争条件。 Add a lock that includes the entire body of get_next(), insert(), and pop_next(). 添加一个包含get_next(),insert()和pop_next()整个主体的锁。

CList is not thread safe - you'll need to use critical sections around those bits of code that check the status of the queue then do something with it. CList不是线程安全的-您需要在代码的那些关键部分使用关键部分来检查队列的状态,然后对其进行处理。

Also, why do you have the bit that works with an item on the queue a different thread than the bit that removes items from the queue? 另外,为什么与队列中用于删除项目的位相比,与队列中的项目使用不同的位?

Don't try to do GUI stuff in a non-GUI thread. 不要尝试在非GUI线程中执行GUI任务。 Only one thread (typically) is the GUI thread. GUI线程只有一个线程(通常)。 The thread with the message pump. 带有消息泵的线程。 In other words the main thread. 换句话说,主线程。

Your worker threads should send some kind of signal to the main thread, which then adds & removes items from the list box. 您的工作线程应向主线程发送某种信号,然后该主线程会在列表框中添加和删除项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM