问题
So i have SEND_SLOT struct:
struct SEND_SLOT
{
SEND_BUFFER buffer;
uint16 index;
CRITICAL_SECTION slotLock;
};
and a connexion struct:
struct connexion
{
...
SEND_SLOT sendSlots[3];
...
}
and in thread A i do:
if(TryEnterCriticalSection(&sendSlots[i]))
{ //Post send request...
WSASend(...);
}
and in thread B i do:
while(...)
{
...
//request finished, data sent, and i get the index to the SEND_SLOT
LeaveCriticalSection(&sendSlots[index]);
...
}
So i'm trying to lock the SEND_SLOT i in thread A and later i want to unlock it, maybe from an other thread, but its not working, each time i try to post new send it locks the first slot even if it hash already been locked and no LeaveCriticalSection has been issued. WHY?
回答1:
No, this is not legal. The documentation for LeaveCriticalSection explains that the same thread that called EnterCriticalSection
must also call LeaveCriticalSection
:
A thread uses the
EnterCriticalSection
orTryEnterCriticalSection
function to acquire ownership of a critical section object. To release its ownership, the thread must callLeaveCriticalSection
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 usingEnterCriticalSection
to wait indefinitely.
The same sort of restriction applies to a mutex. For your case, a semaphore would be more appropriate. MSDN says
only the thread that owns a mutex can successfully call the
ReleaseMutex
function, though any thread can useReleaseSemaphore
to increase the count of a semaphore object.
来源:https://stackoverflow.com/questions/40872941/can-i-entercriticalsections-in-thread-a-then-leavecriticalsections-in-thread