Problems using EnterCriticalSection

前端 未结 6 903
余生分开走
余生分开走 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:26

    I prefer using a separate Acquisition object over your code. Your code if fragile when an exception occurs between the Enter and Leave calls:

    class CS_Acquire {
        CRITICAL_SECTION &cs;
    public:
        CS_Acquire(CRITICAL_SECTION& _cs) : cs(_cs) { EnterCriticalSection(cs); }
        ~CS_Acquire() { LeaveCriticalSection(cs); }
    };
    

    Then in your class methods you would code it as:

    template 
    void SharedVector::PushBack(const T& value) {
       CS_Acquire acquire(&cs);
       vect.push_back(value);
    }
    

提交回复
热议问题