问题
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.
回答1:
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.
回答2:
Check here: http://en.wikipedia.org/wiki/Critical_section
/* Sample C/C++, Unix/Linux */
#include <pthread.h>
/* This is the critical section object (statically allocated). */
static pthread_mutex_t cs_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
void f()
{
/* Enter the critical section -- other threads are locked out */
pthread_mutex_lock( &cs_mutex );
/* Do some thread-safe processing! */
/*Leave the critical section -- other threads can now pthread_mutex_lock() */
pthread_mutex_unlock( &cs_mutex );
}
int main()
{
f();
return 0;
}
回答3:
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.
回答4:
If you are developing programs only for Windows platform, I think the best way is using Win32 API. Otherwise you can use Qt C++ libraries (for that purpose Qt Core is enough).
See also: QMutex and QMutexLocker You can also use: QReadWriteLock
来源:https://stackoverflow.com/questions/3508507/what-are-gcc-on-linuxs-equivalent-to-microsofts-critical-sections