OK to copy a CRITICAL_SECTION?

痞子三分冷 提交于 2019-11-28 03:28:12

问题


One can use a CRITICAL_SECTION variable to get mutual exclusion.

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

I wouldn't be surprised if the answer is "you cannot do that", but it'd be nice to have some sort of official confirmation. I wasn't able to find a statement either way in the documentation.


回答1:


No. A CRITICAL_SECTION cannot be copied. MSDN states this explicitly:

A critical section object cannot be moved or copied.




回答2:


A quick search through the headers reveals that the structure is defined in winnt.h, and this definition clearly seems to indicate that copying the structure wouldn't 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's ClientId->UniqueThread
    HANDLE LockSemaphore;
    ULONG_PTR SpinCount;        // force size on 64-bit systems when packed
} RTL_CRITICAL_SECTION, *PRTL_CRITICAL_SECTION;

That said, I have no idea why these internal counters are stored in a user-space structure, i.e. what will happen if a program modifies these?



来源:https://stackoverflow.com/questions/3269266/ok-to-copy-a-critical-section

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!