Problems using EnterCriticalSection

前端 未结 6 952
余生分开走
余生分开走 2021-02-03 14:51

I need to work with array from several threads, so I use CRITICAL SECTION to give it an exclusive access to the data.
Here is my template:

#include \"std         


        
6条回答
  •  长发绾君心
    2021-02-03 15:18

    Also the code above is not Exception safe.
    There is no guarantee that push_back() pop_back() will not throw. If they do they will leave your critical section permanently locked. You should create a locker class that calls EnterCriticalSection() on construction and LeaveCriticalSection() on destruction.

    Also this makes your methods a lot easier to read. (see below)

    class CriticalSectionLock
    {
        public:
            CriticalSectionLock(CRITICAL_SECTION& cs)
                : criticalSection(cs)
            {
                EnterCriticalSection(&criticalSection);
            }
            ~CriticalSectionLock()
            {
                LeaveCriticalSection(&criticalSection);
            }
        private:
            CRITICAL_SECTION&  criticalSection;
    };
    
    
    // Usage
    template
    unsigned int SharedVector::size() const
    {
        CriticalSectionLock  lock(cs);
        return vect.size();
    }
    

    Another thing you should worry about. Is making sure that when you destroy the object you have ownership and that nobody else tries to take ownership during destruction. Hopefully your DestoryCriticalSection() takes care of this.

提交回复
热议问题