tags:

views:

119

answers:

2

The Microsoft Visual C++ compilers have the EnterCriticalSection and ExitCriticalSection objects to allow for synchronization between threads.

What is the GCC equivalent?

I see references around to __sync_synchronize along with __scoped_lock

In fact I see mention of a number of atomic __sync functions along with a number of __atomic ones.

I actually have been using __sync_fetch_and_add for my atomic increment Should I be using __atomic_add_dispatch instead?
What's the difference?

Which ones should I be using? Are there some constructs in C++ that I can use in both the latest version of GCC and Visual C++ 2010 that are available as I'm going to be writing some cross platform code.

I see boost has some functions available, but for various reasons I'm not allowed to use boost under windows.

+3  A: 

On Linux (and other Unixen) you need to use PThreads, or Posix Threads. There is no equivalent to Critical Sections on Windows; use a Mutex instead.

EDIT: See first comment below -- apparently Posix Mutexes are the same as Win32 Critical Sections in that they are bound to a single process.

Billy ONeal
Actually, POSIX mutexes are equivalent to Win32 Critical Sections (process-bounded); Win32 Mutexes differ from Critical Sections in being cross-process.
MSalters
@MSalters: Ah -- didn't know that. Must smash terminology reuse.
Billy ONeal
@MSalters, Also, Win32 Critical Sections are a lot faster than Win32 mutexes because they are implemented in user space and don't involve the overhead associated with system call. I don't know about Posix mutexes though ?
Tanuj
@Tanuj: You might want to benchmark that statement. Most threading overhead is usually the result of context switches, rather than locking, in any case.
Billy ONeal
@Billy ONeal: it strongly depends on the contention. On a highly contended lock, context-switching to other threads will dominate. On a lighly contended lock, a context switch between user space and kernel space would dominate (which a Win32 Critical Section avoids in the uncontended case)
MSalters
+1  A: 

EnterCriticalSection and the rest of the APIs are Win32 APIs. As far as cross-platform synchronization APIs, I don't think there are any (since you mention you can't use boost). Also, you mentioned cross-platform, does this mean different architectures too (for the gcc part i.e.). I've seen one large implementation where there was a common set of APIs provided which were conditionally compiled to have the native APIs (like fetch_and_add on AIX) or used pthreads the Win32 APIs. I once tried to use posix threads on win32 but ran into a bunch of issues (but that was a very old version). Now YMMV.

Gangadhar