PTHREAD_MUTEX_INITIALIZER 与 pthread_mutex_init ( &mutex, param) [英] PTHREAD_MUTEX_INITIALIZER vs pthread_mutex_init ( &mutex, param)

查看:29
本文介绍了PTHREAD_MUTEX_INITIALIZER 与 pthread_mutex_init ( &mutex, param)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

pthread_mutex_t lock;
pthread_mutex_init ( &lock, NULL);

如果我只使用第一种方法,我就足够安全了吗?

Am I safe enough if I use only the first method ?

注意:我的问题主要是针对非常小的程序,其中我最多要做的是将多个客户端连接到服务器并使用工作线程解决它们的查询.

NOTE: My question mostly refers to very small programs where at the most what I'll do is connect several clients to a server and resolve their inquiries with worker threads.

推荐答案

根据较旧版本的 POSIX 标准,第一个带有初始化程序的方法只能保证使用静态分配的变量,而不是当变量是 auto 时 在函数体中定义的变量.尽管我从未见过不允许这样做的平台,即使对于 auto 变量也是如此,并且此限制已在最新版本的 POSIX 标准中删除.

By older versions of the POSIX standard the first method with an initializer is only guaranteed to work with statically allocated variables, not when the variable is an auto variable that is defined in a function body. Although I have never seen a platform where this would not be allowed, even for auto variables, and this restriction has been removed in the latest version of the POSIX standard.

如果可能的话,static 变体确实更可取,因为它可以更轻松地编写引导程序代码.每当您在运行时输入使用此类互斥锁的代码时,您都可以确信该互斥锁已被初始化.这是多线程上下文中的宝贵信息.

The static variant is really preferable if you may, since it allows to write bootstrap code much easier. Whenever at run time you enter into code that uses such a mutex, you can be assured that the mutex is initialized. This is a precious information in multi-threading context.

当您需要为互斥锁提供特殊属性时,使用 init 函数的方法更可取,例如递归或在进程之间共享,而不仅仅是在线程之间共享.

The method using an init function is preferable when you need special properties for your mutex, such as being recursive e.g or being shareable between processes, not only between threads.

这篇关于PTHREAD_MUTEX_INITIALIZER 与 pthread_mutex_init ( &mutex, param)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆