OK to copy CRITICAL_SECTION?

You can use the CRITICAL_SECTION variable to get a mutual exception.

My question is: Does CRITICAL_SECTION support copying? If I pass one value to another thread, can I know for sure that mutual exclusion will work?

I would not be surprised if the answer is β€œyou cannot do this”, but it would be nice to have some kind of official confirmation. I could not find the statement in the documentation.

+7
c synchronization winapi
source share
2 answers

Not. A CRITICAL_SECTION cannot be copied. MSDN indicates this explicitly :

A critical section object cannot be moved or copied.

+11
source share

A quick search through the headers shows that the structure is defined in winnt.h , and this definition clearly indicates that copying the structure will not work.

 typedef struct _RTL_CRITICAL_SECTION { PRTL_CRITICAL_SECTION_DEBUG DebugInfo; // // The following three fields control entering and exiting the critical // section for the resource // LONG LockCount; LONG RecursionCount; HANDLE OwningThread; // from the thread ClientId->UniqueThread HANDLE LockSemaphore; ULONG_PTR SpinCount; // force size on 64-bit systems when packed } RTL_CRITICAL_SECTION, *PRTL_CRITICAL_SECTION; 

However, I have no idea why these internal counters are stored in the user space structure, i.e. What happens if the program changes them?

+1
source share

All Articles