Balan Narcis Balan Narcis - 1 year ago 68
C++ Question

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

So i have SEND_SLOT struct:

struct SEND_SLOT
uint16 index;

and a connexion struct:

struct connexion
SEND_SLOT sendSlots[3];

and in thread A i do:

{ //Post send request...

and in thread B i do:

//request finished, data sent, and i get the index to the SEND_SLOT

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download