c++ - 我可以在线程 A 中进入 CriticalSection(s),然后在线程 B 中离开 CriticalSection(s)吗?

标签 c++ windows c++11

所以我有 SEND_SLOT 结构:

struct SEND_SLOT
{
    SEND_BUFFER buffer;
    uint16 index;
    CRITICAL_SECTION slotLock;
};

和一个连接结构:

struct connexion
{
    ...
    SEND_SLOT sendSlots[3];
    ...
}

在线程 A 中我做了:

if(TryEnterCriticalSection(&sendSlots[i]))
{  //Post send request...
   WSASend(...);
}

在线程 B 中我做了:

while(...)
{
   ...
   //request finished, data sent, and i get the index to the SEND_SLOT
   LeaveCriticalSection(&sendSlots[index]);
   ...
}

所以我试图在线程 A 中锁定 SEND_SLOT i,稍后我想解锁它,也许是从另一个线程,但它不起作用,每次我尝试发布新发送时它都会锁定第一个插槽,即使它哈希已经被锁定并且没有发出 LeaveCriticalSection。为什么?

最佳答案

不,这是不合法的。 documentation for LeaveCriticalSection解释了调用 EnterCriticalSection 的同一个线程也必须调用 LeaveCriticalSection:

A thread uses the EnterCriticalSection or TryEnterCriticalSection function to acquire ownership of a critical section object. To release its ownership, the thread must call LeaveCriticalSection once for each time that it entered the critical section.

If a thread calls LeaveCriticalSection when it does not have ownership of the specified critical section object, an error occurs that may cause another thread using EnterCriticalSection to wait indefinitely.

同样的限制适用于互斥量。对于您的情况,信号量会更合适。 MSDN

only the thread that owns a mutex can successfully call the ReleaseMutex function, though any thread can use ReleaseSemaphore to increase the count of a semaphore object.

关于c++ - 我可以在线程 A 中进入 CriticalSection(s),然后在线程 B 中离开 CriticalSection(s)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40872941/

相关文章:

c++ - 相等 vector 的返回值 std::mismatch

c++ - 使用可选参数覆盖虚函数

c++ - 切换到 clang 3.4 和 libc++ 时找不到标准 header

windows - 在本地使用 Mercurial 并在远程使用 SVN?

python - 如何用 python Tkinter 隐藏 Windows 控制台?

c++ - 括号后面的类名是什么类型

c++ - 基于范围的 for 循环和 ADL

c++ - 在基于范围内自动传递的参数

c++ - 需要洗牌并打印

windows - Windows 上的 imapclient 错误