Problems using EnterCriticalSection

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

    I see you have declared an empty copy constructor:

    SharedVector(const SharedVector& rhs) {}
    

    As I'm sure you are aware, this function does nothing, and it also leaves cs uninitialised. Because your class contains an instance of a CRITICAL_SECTION, you must be sure to disallow copy constructor and assignment operator calls unless you are going to implement them completely. You can do this by placing the following declarations in the private section of your class:

    SharedVector(const SharedVector &);
    SharedVector &operator=(const SharedVector &);
    

    This prevents the compiler from auto-generating incorrect versions of these methods, and also prevents you from calling them in other code you write (because these are only declarations, but not definitions with {} code blocks).

    Also, as Arnout mentioned, the constructor that takes a CRITICAL_SECTION& argument seems wrong. What your implementation does is copy the passed-in critical section to cs (which is not a valid thing to do with a CRITICAL_SECTION), then calls InitializeCriticalSection(&cs) which overwrites the copy you just did and creates a new critical section. To the caller who passed in a critical section, this seems to do the wrong thing by effectively ignoring whatever was passed in.

提交回复
热议问题