Andreas
Andreas

Reputation: 10077

LeaveCriticalSection() yield

I have two threads that share a critical section. Thread A permanently keeps a lock on the critical section but runs the following code about 50 times per second to give thread B a chance to step in:

LeaveCriticalSection(sec);
EnterCriticalSection(sec);

Using this code, however, thread B doesn't ever seem to get a chance to acquire the critical section. Instead, the call to EnterCriticalSection(sec) in thread B will block that thread forever, although thread A is unlocking the critical section 50 times per second.

I know that the interval between the calls to LeaveCriticalSection() and EnterCriticalSection() in the 50hz timer in thread A is as brief as it gets, but I'd expect the LeaveCriticalSection() call to yield to other threads waiting on the critical section before continuing execution.

Is LeaveCriticalSection() not supposed to work like this? If so, is there a way to explicitly yield to other threads after releasing the critical section lock? POSIX has something like sched_yield() for that but I think it's not even necessary on POSIX because pthread_mutex_unlock() will give other threads a chance to step in automatically.

But it doesn't seem to work on Windows (or there is something wrong with my code). Can anybody shed some light onto this?

Thanks!

Upvotes: 0

Views: 431

Answers (2)

avo
avo

Reputation: 10711

If you want to yield on such a tight loop, you could probably achieve that using mutex instead of critical section (disclaimer: I haven't verified that).

Upvotes: 0

HerrJoebob
HerrJoebob

Reputation: 2313

Thread A probably needs to yield its timeslice with a Sleep(0) or similar call. Critical section operations normally stay in user mode code, so they don't make a transition to the kernel and thus don't give up thread A's timeslice.

Upvotes: 3

Related Questions