STL & Threads

Started by
21 comments, last by Shannon Barber 23 years, 5 months ago
The differences under the hood are:

(This is all pseudo code and is probably close to how Windows does it. You want to acquire a critical section in as few cycles as possible, so it''s probably 100% assembly. Some extra details are left out.)

void EnterCriticalSection(CRITICAL_SECTION* pcs){    if(InterlockedExchange(pcs->lock, 1)==1)    {        // Lock is held, transition to kernel mode and        // either reacquire or block.        SystemCall(ACQUIRE_CS, pcs);    }}BOOL TryEnterCriticalSection(CRITICAL_SECTION* pcs){    return InterlockedExchange(pcs->lock, 1)} 


The only difference is Enter transitions to kernel mode and blocks if the lock is held. Note that we have to check the lock again in kernel mode, because we may have been interrupted and the lock released sometime after the initial InterlockedExchange().

Also, I doubt Win9x transitions to kernel mode, but that involves its design (user programs have too many privileges.)
Advertisement
Hmm... That''s interesting... thanks for the info! However, I was thinking more along the lines of differences between WaitForSingleObject(handle, 0) and TryEnterCriticalSection, but you said that WaitForSingleObject enters kernel mode anyway like EnterCriticalSection? or is it more like TryEnterCriticalSection?


- null_pointer
Sabre Multimedia
WaitForSingleObject always enters kernel mode. The handle passed to it is a kernel object, so it can''t be accessed from user mode. That''s why critical sections are faster, in the common case of no lock contention, you do not do a mode switch (which can be costly.)

This topic is closed to new replies.

Advertisement