Problems using EnterCriticalSection

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

    Just declare cs as:

    mutable CRITICAL_SECTION cs;
    

    or else remove the const clause on size()

    Entering a critical section modifies the CRITICAL_SECTION, and leaving modifies it again. Since entering and leaving a critical section doesn't make the size() method call logically non-const, I'd say leave it declared const, and make cs mutable. This is the type of situation mutable was introduced for.

    Also - take a look at Martin York's and Joe Mucchiello's suggestions - use RAII whenever possible to deal with any kind of resources that need to be cleaned up. This works just as well for critical sections as it does for pointers and file handles.

提交回复
热议问题