我在网上看到的大多数示例都有 pthread_mutex_t 位于全局空间中文件的顶部,我想我在某处读到 Linux 互斥锁必须是全局的。这是真的?
编辑:我有一些 Win32 多线程代码要移植到 Linux。对于 Windows 代码,有几个封装函数可以封装互斥体创建和锁定/解锁等内容。我的理解是,通过 Windows 中的一个 API 调用创建的每个同步原语都会Create()
返回一个 HANDLE,该 HANDLE 可以存储在实例字段中,然后稍后使用。在这种情况下,它在 Lock() 函数中使用,该函数是 WaitForSingleObject() 的包装器。对于 Linux,我是否可以简单地将互斥锁存储在实例字段中并调用pthread_mutex_lock()/pthread_cond_wait()
Lock() 函数并期望与 Windows 上的行为相同?
Nv_Mutex::Nv_Mutex(Nv_XprocessID name)
{
#if defined(WIN32)
if((handle = ::CreateMutexA(0, false, name)) == NULL)
{
throw Nv_EXCEPTION(XCPT_ResourceAllocationFailure, GetLastError());
}
isCreator = !(::GetLastError() == ERROR_ALREADY_EXISTS);
#else
if (name == Nv_XprocessID_NULL) {
/*
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // Fast
pthread_mutex_t recmutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; // Recursive
pthread_mutex_t errchkmutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP; // Errorcheck
*/
mutex = PTHREAD_MUTEX_INITIALIZER;
// attributes??
if (pthread_mutex_init(&mutex, NULL) != 0) {
throw Nv_EXCEPTION(XCPT_ResourceAllocationFailure, GetLastError());
}
}
else {
// insert code for named mutex (needed for shared mutex across processes) here.
}
//isCreator = !(GetLastError() == EBUSY);
#endif
}
bool
Nv_Mutex::Lock(const char *f, int l, Nv_uint32 timeout)
{
switch(WaitForSingleObject(handle, timeout))
{
case WAIT_OBJECT_0:
file = f;
line = l;
return true;
case WAIT_TIMEOUT:
return false;
}
throw Nv_EXCEPTION(XCPT_WaitFailed, GetLastError());
}