[英]What happens if pthread_key_delete is called on a key after a failed pthread_key_create?
Suppose the following code: 假设以下代码:
pthread_key_t key;
pthread_key_create(&key, NULL); /* failure here */
pthread_key_delete(key);
If pthread_key_create
fails, is the call to pthread_key_delete
considered undefined behavior ? 如果
pthread_key_create
失败,对pthread_key_delete
的调用是否被视为未定义的行为 ? How about if pthread_key_create
is commented out? 如果
pthread_key_create
被注释掉怎么样?
The pthread_key_delete section of the POSIX standard states: POSIX标准的pthread_key_delete部分指出:
The pthread_key_delete() function shall delete a thread-specific data key previously returned by pthread_key_create().
pthread_key_delete()函数应删除先前由pthread_key_create()返回的特定于线程的数据密钥。
Since pthread_key_delete
expects a thread-specific data key previously returned by pthread_key_create
, I'm afraid calling pthread_key_delete
on a key that was not returned by pthread_key_create
can lead to undefined behavior. 由于
pthread_key_delete
需要先前由pthread_key_create
返回的特定于线程的数据密钥,因此我担心在pthread_key_delete
未返回的密钥上调用pthread_key_create
会导致未定义的行为。
Yes, it is implicitly undefined behavior, to the extent that the standard you link doesn't define what happens in that use case. 是的,它是隐式未定义的行为,只要您链接的标准没有定义该用例中发生的事情。
The SUSv7, however, is explicit in its discussion of pthread_key_delete
, saying plainly in its CHANGE HISTORY for Issue 7 that: 然而,SUSv7在讨论
pthread_key_delete
是明确的,在第7期的CHANGE HISTORY中明确地说:
The [EINVAL] error for a key value not obtained from pthread_key_create() or a key deleted with pthread_key_delete() is removed;
未删除从pthread_key_create()获取的键值或使用pthread_key_delete()删除的键的[EINVAL]错误; this condition results in undefined behavior.
这种情况会导致不确定的行为。
By looking at the source code of pthread_key_create and pthread_key_delete it seems that pthread_key_create is returning a memory location and filling in other fields of "key" structure, which is opaque like everything else in posix. 通过查看pthread_key_create和pthread_key_delete的源代码,似乎pthread_key_create返回一个内存位置并填充“key”结构的其他字段,这与posix中的其他所有字段一样不透明。
pthread_key_delete expects the key structure fields to be populated/set with valid data to search for the memory location. pthread_key_delete期望使用有效数据填充/设置关键结构字段以搜索内存位置。 So it seems calling pthread_key_delete after a failed pthread_key_create causes undefined behavior.
因此,在失败的pthread_key_create导致未定义的行为后,似乎调用pthread_key_delete。 Here is one more link that seems to support by opinion.
这是另一个似乎支持意见的链接。
How does pthread_key_t and the method pthread_key_create work? pthread_key_t和方法pthread_key_create如何工作?
I hope this helps. 我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.