什么是Linux上的gcc相当于微软的关键部分?

Mat*_*att 9 multithreading gcc synchronization posix

Microsoft Visual C++编译器具有 允许线程之间同步的EnterCriticalSectionExitCriticalSection对象.

什么是GCC等价物?

我看到了__sync_synchronize与之相关的参考资料__scoped_lock

事实上,我看到提到了许多原子__sync功能以及许多原子功能 __atomic.

我实际上一直在使用__sync_fetch_and_add我的原子增量我应该使用__atomic_add_dispatch吗?
有什么不同?

我应该使用哪些?我是否可以在最新版本的GCC和Visual C++ 2010中使用C++中的一些构造,因为我将编写一些跨平台代码.

我看到boost有一些功能可用,但出于各种原因我不允许在windows下使用boost.

Bil*_*eal 19

在Linux(和其他Unixen)上,您需要使用PThreads或Posix Threads.没有相当于Windows上的关键部分; 请改用互斥锁.

编辑:请参阅下面的第一条评论 - 显然Posix Mutexes与Win32 Critical Sections相同,因为它们绑定到一个进程.

  • 实际上,POSIX互斥体相当于Win32关键部分(进程有界); Win32 Mutexes在跨进程中与Critical Sections不同. (6认同)
  • 我做了一些测试,在许多线程的激烈竞争条件下,windows的关键部分明显快于linux mutex (3认同)
  • @Arsen:两种方式都不会让我感到惊讶.对于我(非常有限的)理解,他们是不同的野兽.我知道Windows人员花了很多时间来优化锁的行为方式. (2认同)

Tut*_*men 8

点击此处: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;
}
Run Code Online (Sandbox Code Playgroud)