C ++ Critical Section无效

时间:2011-10-07 15:00:21

标签: c++ vector critical-section

我的关键部分代码不起作用!!! Backgrounder.run能够修改MESSAGE_QUEUE g_msgQueue并且还没有调用LockSections析构函数!!!

额外代码:

typedef std::vector<int> MESSAGE_LIST; // SHARED OBJECT .. MUST LOCK!

class MESSAGE_QUEUE : MESSAGE_LIST{
public:
    MESSAGE_LIST * m_pList;
    MESSAGE_QUEUE(MESSAGE_LIST* pList){ m_pList = pList; }
    ~MESSAGE_QUEUE(){ }
    /* This class will be shared between threads that means any 
     * attempt to access it MUST be inside a critical section. 
     */
    void Add( int messageCode ){ if(m_pList) m_pList->push_back(messageCode); }

    int getLast()
    { 
      if(m_pList){ 
        if(m_pList->size() == 1){ 
          Add(0x0); 
        } 
        m_pList->pop_back(); 
        return m_pList->back(); 
      } 
    }
    void removeLast()
    { 
      if(m_pList){ 
        m_pList->erase(m_pList->end()-1,m_pList->end()); 
      } 
    }
};

class Backgrounder{
public:
    MESSAGE_QUEUE* m_pMsgQueue;
    static void __cdecl Run( void* args){
        MESSAGE_QUEUE* s_pMsgQueue = (MESSAGE_QUEUE*)args;
        if(s_pMsgQueue->getLast() == 0x45)printf("It's a success!");
        else printf("It's a trap!");
    }
    Backgrounder(MESSAGE_QUEUE* pMsgQueue) 
    { 
      m_pMsgQueue = pMsgQueue; 
      _beginthread(Run,0,(void*)m_pMsgQueue); 
    }
    ~Backgrounder(){ }
};

int main(){

    MESSAGE_LIST g_List;
    CriticalSection crt;
    ErrorHandler err;
    LockSection lc(&crt,&err); // Does not work , see question #2
    MESSAGE_QUEUE g_msgQueue(&g_List);
    g_msgQueue.Add(0x45); 
    printf("%d",g_msgQueue.getLast()); 
    Backgrounder back_thread(&g_msgQueue);


    while(!kbhit());
    return 0;
}

#ifndef CRITICALSECTION_H
#define CRITICALSECTION_H
#include <windows.h>
#include "ErrorHandler.h"


class CriticalSection{
    long m_nLockCount;
    long m_nThreadId;
    typedef CRITICAL_SECTION cs;
    cs m_tCS;
public:
    CriticalSection(){
        ::InitializeCriticalSection(&m_tCS);
        m_nLockCount = 0;
        m_nThreadId = 0;
    }
    ~CriticalSection(){ ::DeleteCriticalSection(&m_tCS); }
    void Enter(){ ::EnterCriticalSection(&m_tCS);  }
    void Leave(){  ::LeaveCriticalSection(&m_tCS); }
    void Try();
};


class LockSection{
    CriticalSection* m_pCS;
    ErrorHandler * m_pErrorHandler;
    bool m_bIsClosed;
public:
    LockSection(CriticalSection* pCS,ErrorHandler* pErrorHandler){
        m_bIsClosed = false;
        m_pCS = pCS;
        m_pErrorHandler = pErrorHandler;
            // 0x1AE is code prefix for critical section header
        if(!m_pCS)m_pErrorHandler->Add(0x1AE1); 
        if(m_pCS)m_pCS->Enter();
    }
    ~LockSection(){
        if(!m_pCS)m_pErrorHandler->Add(0x1AE2);
        if(m_pCS && m_bIsClosed == false)m_pCS->Leave();
    }
    void ForceCSectionClose(){
        if(!m_pCS)m_pErrorHandler->Add(0x1AE3);
        if(m_pCS){m_pCS->Leave();m_bIsClosed = true;}
    }
};

/*

Safe class basic structure;

class SafeObj
{
     CriticalSection m_cs;

public:
    void SafeMethod()
    {
        LockSection myLock(&m_cs);
        //add code to implement the method ...

    }
};



*/
#endif

4 个答案:

答案 0 :(得分:3)

两个问题合二为一。我不知道第一个,但关键部分很容易解释。后台线程没有尝试声明锁定,因此当然不会被阻止。您需要使关键部分对象crt对线程可见,以便它可以锁定它。

使用此锁类的方法是,您希望序列化的每个代码段都必须创建一个LockSection对象并保持该对象,直到序列化块结束:

主题1:

{
    LockSection lc(&crt,&err);
    //operate on shared object from thread 1
}

主题2:

{
    LockSection lc(&crt,&err);
    //operate on shared object from thread 2
}

请注意,它必须与要序列化的每个代码块中使用的关键部分实例crt相同。

答案 1 :(得分:3)

此代码存在许多问题。

首先,从标准容器中获取几乎总是一个糟糕的主意。在这种情况下,您使用私有继承,这可以减少问题,但不会完全消除它们。在任何情况下,你似乎都没有把继承放在很多(任何?)的使用上。即使您从MESSAGE_QUEUE(实际上是MESSAGE_LIST)派生了std::vector<int>,您仍然可以将指向MESSAGE_LIST的实例的指针嵌入到MESSAGE_QUEUE

其次,如果您要使用队列在线程之间进行通信(我认为 通常是一个好主意),您应该在队列操作中固有锁定,而不是要求每个线程自己正确管理锁定。

第三,vector不是一个特别适合表示队列的数据结构,除非你打算使它固定大小,并且大致像环形缓冲区一样使用它。这也不是一个坏主意,但它与你所做的完全不同。如果你想让尺寸变得动态,你可能会更好地开始使用deque。

第四,错误处理中的幻数(0x1AE1,0x1AE2等)非常不透明。至少,您需要来提供这些有意义的名称。您所拥有的一条评论 not 可以在任何接近清晰的地方使用。

最后,如果您要为线程安全队列编写代码会遇到麻烦,那么您也可以将其设置为通用,以便它可以保存您想要的任何类型的数据,而不是将其专用于一种特定的类型。

最终,您的代码似乎没有为客户端节省大量工作或直接使用Windows功能的麻烦。在大多数情况下,您只是以略微不同的名称提供相同的功能。

IMO,一个线程安全的队列应该在内部处理几乎所有的工作,这样客户端代码可以像使用任何其他队列那样使用它。

// Warning: untested code.
// Assumes: `T::T(T const &) throw()` 
//
template <class T>
class queue { 
    std::deque<T> data;
    CRITICAL_SECTION cs;
    HANDLE semaphore;
public:
    queue() { 
        InitializeCriticalSection(&cs); 
        semaphore = CreateSemaphore(NULL, 0, 2048, NULL);
    }

    ~queue() { 
        DeleteCriticalSection(&cs); 
        CloseHandle(semaphore);
    }

    void push(T const &item) {         
        EnterCriticalSection(&cs);
        data.push_back(item);
        LeaveCriticalSection(&cs);
        ReleaseSemaphore(semaphore, 1, NULL);
    }

    T pop() { 
        WaitForSingleObject(semaphore, INFINITE);
        EnterCriticalSection(&cs);
        T item = data.front();
        data.pop_front();
        LeaveCriticalSection(&cs);
        return item;
    }
};



HANDLE done;

typedef queue<int> msgQ;

enum commands { quit, print };

void backgrounder(void *qq) { 

  // I haven't quite puzzled out what your background thread
  // was supposed to do, so I've kept it really simple, executing only
  // the two commands listed above.
  msgQ *q = (msgQ *)qq;
  int command;

  while (quit != (command = q->pop()))
      printf("Print\n");
  SetEvent(done);
}

int main() { 
    msgQ q;
    done = CreateEvent(NULL, false, false, NULL);
    _beginthread(backgrounder, 0, (void*)&q);
    for (int i=0; i<20; i++)
        q.push(print);
    q.push(quit);
    WaitForSingleObject(done, INFINITE);
    return 0;
}

答案 2 :(得分:2)

您的后台线程需要访问相同的CriticalSection对象,并且需要创建LockSection个对象来锁定它 - 锁定是协作的。

答案 3 :(得分:1)

您试图在弹出之后返回的最后一个元素。