gpt4 book ai didi

c - 再次初始化相同的互斥体

转载 作者:太空宇宙 更新时间:2023-11-04 01:02:19 26 4
gpt4 key购买 nike

当我再次初始化相同的互斥变量时会发生什么?根据 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;
}

提前致谢!

最佳答案

请注意,它说“如果...,pthread_mutex_init() 函数可能 失败”。这意味着不需要实现来执行这些检查,显然你的不需要。

看看 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] 位于“可能失败”部分。所以这不是保证,而只是允许实现做的事情。

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

此外,pthread_mutex_init 实际上返回错误代码,如果有错误代码,它不会设置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.

关于c - 再次初始化相同的互斥体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33690212/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com