0

我的临界区代码不起作用!!!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

4 回答 4

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要序列化的每个代码块中使用的临界区实例相同。

于 2011-10-07T15:04:11.523 回答
3

这段代码有很多问题。

首先,从标准容器派生几乎总是一个糟糕的主意。在这种情况下,您使用的是私有继承,这减少了问题,但并没有完全消除它们。无论如何,您似乎并没有过多地(任何?)使用继承。即使您已经派生了MESSAGE_QUEUEfrom MESSAGE_LIST(实际上是std::vector<int>),您还是将指向 a 实例的指针嵌入到MESSAGE_LIST其中MESSAGE_QUEUE

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

第三,vector无论如何 a 都不是一个特别适合表示队列的数据结构,除非您要使其大小固定,并且大致像环形缓冲区一样使用它。这也不是一个坏主意,但它与你所做的有很大不同。如果要使大小动态化,则最好从双端队列开始。

第四,错误处理中的幻数(0x1AE1、0x1AE2 等)非常不透明。至少,你需要给这些有意义的名字。您拥有的一条评论并没有使使用任何地方接近清晰。

最后,如果您要费尽心思为线程安全队列编写代码,您不妨将其设为通用,这样它基本上可以保存您想要的任何类型的数据,而不是将其专用于一种特定类型.

最终,与直接使用 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;
}
于 2011-10-07T16:46:24.410 回答
2

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

于 2011-10-07T15:06:20.923 回答
1

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

于 2011-10-07T15:04:24.733 回答