Balan Narcis Balan Narcis - 6 days ago 5
C++ Question

Can I EnterCriticalSection(s) in thread A then LeaveCriticalSection(s) in thread B?

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?

Answer

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 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.

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 use ReleaseSemaphore to increase the count of a semaphore object.

Comments