You can (sort of) simulate a try with a timeout using TryEnterCriticalSection
, but for the most part, if you want a timeout you might be better off using a mutex
instead (when you get down to it, a critical section is mostly a wrapper around a mutex).
Another possibility would be to use the Win32 pthreads library, which will probably let your Linux code compile under Win32 unchanged (and you'd simply eliminate your own Win32 code).
This is pretty similar to the threading support that's been added to the C++ 0x library, though it doesn't (even try to) follow the new standard precisely. If you want to follow the standard, you could use Anthony Williams' Just Thread library (warning: fairly reasonably priced, but not free in either sense).
Edit (in response to Billy O'neal's questions): Thinking about it a bit more, there actually is source code easily available that shows most of what's going on. The CRITICAL_SECTION data structure is defined in winbase.h as a typedef of an RTL_CRITICAL_SECTION. That, in turn, is defined in WinNT.h as:
typedef struct _RTL_CRITICAL_SECTION {
PRTL_CRITICAL_SECTION_DEBUG DebugInfo;
//
// The following three fields control entering and exiting the critical
// section for the resource
//
LONG LockCount;
LONG RecursionCount;
HANDLE OwningThread; // from the thread's ClientId->UniqueThread
HANDLE LockSemaphore;
ULONG_PTR SpinCount; // force size on 64-bit systems when packed
} RTL_CRITICAL_SECTION, *PRTL_CRITICAL_SECTION;
If memory serves, the basic idea of how this is used runs something like:
- If this thread already owns the critical section, increment RecursionCount and return
- Otherwise, do SpinCount attempts to enter CS via fast path using atomic ops on LockCount
- Otherwise, wait on LockSemaphore