日期:2014-05-16  浏览次数:20620 次

关于phtread_mutext_t结构初始化的疑惑
从环高里看见,该结构体可以有静态与动态两种初始化方式。当该类型的变量被声明为静态全局变量时,我们应该使用宏PTHREAD_MUTEX_INITIALIZER在变量定义的时候对它进行初始化,而如果是利用malloc动态分配的变量,则须利用init函数和destroy函数进行初始化和销毁。
我不明白为什么要分静态初始化和动态初始化两种方式,直接都用init函数不就可以了吗?而在静态初始化时为什么不需要destroy呢?

------解决方案--------------------
也许你还没有man pthread.h 看过里面有多少配置mutexattr的函数,所以意识不到pthread_mutex_init的用途。

int pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr);

重点关注第二个参数。

另外,这是静态初始化存在的必要性:
Providing for static initialization of statically allocated synchronization objects allows modules with private static synchronization variables to avoid
runtime initialization tests and overhead.

再另外,没有规定说静态初始化的不可以destroy,它在不使用时理所应当主动destroy。但为什么我们一般不主动detroy是因为我们已经将它静态初始化了,说明它的用途就是伴随着程序出生到结束的,一般没有释放的理由。 如果你detroy了一个静态初始化的mutex, 并希望再次使用它,请重新对其mutex_init,原因:


In cases where default mutex attributes are appropriate, the macro PTHREAD_MUTEX_INITIALIZER can be used to initialize mutexes that are statically allocated.
The effect shall be equivalent to dynamic initialization by a call to pthread_mutex_init() with parameter attr specified as NULL, except that no error checks
are performed.