c++ - 如何确保共享堆栈分配的 pthread_mutex_t 的单一初始化? (C++)

标签 c++ multithreading pthreads mutex

确保堆栈分配的 pthread_mutex_t 对象在多线程环境中仅初始化一次的可取/标准方法是什么?

pthread_mutex_init() 手册页说:

Attempting to initialise an already initialised mutex results in undefined behaviour.

我有一个编译成共享库的.cpp 文件。该文件的简化形式是:

#include <pthread.h>

static pthread_mutex_t g_mutex;

int initialize()
{
  pthread_mutex_init( &g_mutex, NULL );
  pthread_mutex_lock( &g_mutex );
  // Do init stuff.
  pthread_mutex_unlock( &g_mutex );
  return 0;
}

initialize() 可以在多线程环境中调用。因此,pthread_mutex_init() 可能会在同一个对象上多次调用,这是未定义的行为,如上所述。所以这需要线程安全......通过使用另一个互斥锁。但是谁会以线程安全的方式初始化那个互斥量,无穷无尽...?

在全局范围(即与 pthread_mutex_t 对象声明相同的范围)调用 pthread_mutex_init() 是否合法,这是否被认为是“正确的” "这种情况的解决方案?

#include <pthread.h>

static pthread_mutex_t g_mutex;
static int g_res = pthread_mutex_init( &g_mutex, NULL );

int initialize()
{
  // g_mutex already initialized (?) so no need to do so here.
  pthread_mutex_lock( &g_mutex );
  // Do init stuff.
  pthread_mutex_unlock( &g_mutex );
  return 0;
}

我尝试过的:

我编译并运行了第二个代码块,都成功了。

但我仍然想问社区,因为我有点不清楚在全局范围内调用 pthread_mutex_init() 函数的合法性,我想确保可执行文件没有'由于未定义的行为,它似乎可以正常工作。

最佳答案

Is it legal to call pthread_mutex_init() at the global scope (i.e. the same scope as the pthread_mutex_t object declaration) as below, and is this considered a "correct" solution to this situation?

这在 C 中是不合法的,但在 C++ 中是可以的。但是,由于您正在使用默认属性初始化互斥锁,因此最好使用初始化宏:

static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;

关于c++ - 如何确保共享堆栈分配的 pthread_mutex_t 的单一初始化? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42818852/

相关文章:

c - Pthreads 而不是共享变量

java - 大型数组中元素的并行求和

c - P线程介绍

c++ - 我们如何并行运行算法的 n 个实例并以有效的方式计算结果函数的平均值?

c++ - 命令 'cin' 和 'cout' 不工作

打印 header 中声明的变量时 C++ 崩溃

c - 在多线程应用程序中将日志写入文件

c++ - 这个继承类会调用哪个方法(虚函数)? C++

java - 在多线程情况下,httpurlconnection 未给出正确的响应代码

multithreading - 乐观并发控制澄清