gpt4 book ai didi

c++ - EnterCriticalSection 似乎没有阻塞

转载 作者:可可西里 更新时间:2023-11-01 14:44:57 24 4
gpt4 key购买 nike

我有以下代码来创建线程来完成一些工作(为清楚起见,省略了部分)。

 CRITICAL_SECTION gCS;

class Locker
{
public:
Locker(CRITICAL_SECTION& cs): m_cs(cs)
{
EnterCriticalSection(&m_cs);
}
~Locker()
{
LeaveCriticalSection(&m_cs);
}
private:
CRITICAL_SECTION m_cs;
};

...

HRESULT MyClass::FinalConstruct()
{
InitializeCriticalSection(&gCS);
}

...

DWORD WINAPI MyClass::CreateThread()
{

hWriteReceiptThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
MyClass::RunThread, // thread function name
NULL, // argument to thread function
0, // use default creation flags
&dwThreadId); // returns the thread identifier
return 0;
}


DWORD WINAPI MyClass::RunThread(LPVOID args)
{
{
LogInfo("getting lock for critical Section");
Locker lock(gCS);
EnterCriticalSection(&gCS);
LogInfo("entered Critical Section");

//... do lots of stuff

LogInfo("leaving critical section");
LeaveCriticalSection(&gCS);
LogInfo("left critical section");
}
}

当它运行时,会出现以下打印语句(每个打印语句都会在语句之前打印从 GetCurrentThreadId() 返回的数字。看起来好像关键部分没有效果。例如 Thread 7608 获得锁,然后后面的两个线程在完成之前也获得锁。任何人都可以深入了解这是如何发生的吗?

 16004 Critical section initialised
7608 getting lock for critical Section
7608 Entered Critical Section
11412 getting lock for critical Section
11412 Entered Critical Section
12860 getting lock for critical Section
6552 getting lock for critical Section
6552 Entered Critical Section
5524 getting lock for critical Section
5524 Entered Critical Section
7608 leaving critical section
7608 left critical section

谢谢

最佳答案

根据 the documentation :

A critical section object cannot be moved or copied.

您正在复制关键部分并对拷贝进行操作。

Locker(CRITICAL_SECTION& cs): m_cs(cs)
^^^^^^^^
...
CRITICAL_SECTION m_cs;

您可能想复制引用,而不是实际的关键部分。

CRITICAL_SECTION& m_cs;
^ reference

关于c++ - EnterCriticalSection 似乎没有阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26436411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com