再次初始化相同的互斥量

Initializing the same mutex again

当我再次初始化相同的互斥变量时会发生什么? 根据 pthread_mutex_init() 手册页 - http://linux.die.net/man/3/pthread_mutex_init

它应该失败,errno 设置为 EBUSY

为什么我看不到这种行为?下面的代码执行得很好。

lock = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
if (pthread_mutex_init((pthread_mutex_t*)lock, NULL) != 0)
{
    printf("\n mutex init failed\n");
    return 1;
}

if (pthread_mutex_init((pthread_mutex_t*)lock, NULL) != 0)
{
    printf("\n mutex init failed %d\n", errno);
    return 1;
}

提前致谢!

请注意它说 "The pthread_mutex_init() function may fail if ..."。这意味着执行这些检查不需要实现,显然你的不需要。

查看 corresponding POSIX page 的错误列表:

The pthread_mutex_init() function will fail if:

[EAGAIN] The system lacked the necessary resources (other than memory) to initialise another mutex.

[ENOMEM] Insufficient memory exists to initialise the mutex.

[EPERM] The caller does not have the privilege to perform the operation.

The pthread_mutex_init() function may fail if:

[EBUSY] The implementation has detected an attempt to re-initialise the object referenced by mutex, a previously initialised, but not yet destroyed, mutex.

[EINVAL] The value specified by attr is invalid.

您会注意到 [EBUSY] 在 "may fail" 部分。所以这不是保证,而只是允许实现的事情。

对于不习惯阅读标准或正式 API 文档的人来说,这种事情常常有点令人惊讶。措辞的选择是经过深思熟虑的, "may" 这个词通常表示允许发生的事情。 "will"(或不太常见的 "shall")一词用于表示保证。

另外,pthread_mutex_init其实是returns错误码,如果有的话,不设置errno。来自您引用的手册页:

If successful, the pthread_mutex_destroy() and pthread_mutex_init() functions shall return zero; otherwise, an error number shall be returned to indicate the error.