是否应该避免使用 PTHREAD_MUTEX_INITIALIZER 进行 pthread_mutex 静态初始化?
使用 PTHREAD_MUTEX_INITIALIZER 静态初始化 pthread 互斥锁并直接传递它们进行锁定是否存在任何已知问题?
我在一些网站上读到,这不能在所有平台上得到保证,并且在帮助页面中也有以下注释:
注意:使用 PTHREAD_MUTEX_INITIALIZER 的互斥体初始化不会立即初始化互斥体。相反,在第一次使用时,pthread_mutex_lock() 或 pthread_mutex_trylock() 函数会分支到慢速路径并导致互斥体的初始化。由于互斥体不仅仅是一个简单的内存对象,并且需要系统分配一些资源,因此尝试对使用 PTHREAD_MUTEX_INITIALER 静态初始化且尚未锁定的互斥体调用 pthread_mutex_destroy() 或 pthread_mutex_unlock() 会导致 EINVAL 错误。
那么,如果两个线程在静态初始化后调用pthread_mutex_lock,会导致什么问题吗?
Are there any known problems of initialiazing pthread mutexes statically using PTHREAD_MUTEX_INITIALIZER and passing them directly for locking?
I read in some sites that this cannot be guaranteed on all platforms and also in the help page the below note is there:
Note: Mutex initialization using the PTHREAD_MUTEX_INITIALIZER does not immediately initialize the mutex. Instead, on first use, the pthread_mutex_lock() or pthread_mutex_trylock() functions branch into a slow path and cause the initialization of the mutex. Because a mutex is not just a simple memory object and requires that some resources be allocated by the system, an attempt to call pthread_mutex_destroy() or pthread_mutex_unlock() on a mutex that was statically initialized using PTHREAD_MUTEX_INITIALER and was not yet locked causes an EINVAL error.
So, if two threads call pthread_mutex_lock after static initialization, will it lead to any problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这不是问题。
给定的 POSIX 线程定义了 API,但没有定义实现。如果某些实现选择某种特殊方法,这不是问题。但应该保证调用 pthread_mutex_lock 的正确行为。
I think it is not a problem.
Given POSIX thread defines the API but not the implementation. it is not an issue if some implementations choose an some special approach. But the correct behavior of calling pthread_mutex_lock should be guaranteed.