0

我在网上看到的大多数示例都有 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());
}
4

2 回答 2

1

不,它们可以限定范围。实际的互斥指针没有什么特别之处。

于 2012-12-06T04:30:52.853 回答
1

You have the requirement a bit wrong. Mutexes do not need to be global, however, you cannot statically initialize a non-static mutex. But you do not need to statically initialize a mutex prior to calling pthread_mutex_init on it, because that initializes it. So just don't use static initializers and instead call pthread_mutex_init.

It will actually work, but this is by luck due to the details of the implementation. Please don't rely on an implementation detail.

Static initialization is legal only for statically ALLOCATED storage[.] ... Although C syntax allows using the static initialization macros on "automatic" variables, this is specifically prohibited by the POSIX standard. It's not correct, and it's not portable. - David Butenhof

于 2012-12-06T19:18:54.930 回答