确保堆栈分配的 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 thepthread_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/