我在Web上看到的大多數示例都有pthread_mutex_t坐在全局空間的文件頂部,我認爲我讀了Linux互斥體必須是全局的地方。這是真的?Linux互斥鎖必須是全局的?
編輯: 我有一些Win32多線程代碼,我正在移植到Linux。對於windows代碼,有幾個封裝函數封裝了互斥鎖創建和鎖定/解鎖等內容。我的理解是,通過Windows中的某個Create()
API調用創建的每個同步基元都會返回一個HANDLE,該HANDLE可以存儲在實例字段中,稍後再使用。在這種情況下,它在Lock()函數中使用,它是WaitForSingleObject()的封裝。對於Linux,我是否可以簡單地將互斥量存儲在實例字段中,並在Lock()函數中調用pthread_mutex_lock()/pthread_cond_wait()
,並期望與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());
}