【问题标题】:when pthread_attr_t is not NULL?当 pthread_attr_t 不为 NULL 时?
【发布时间】:2017-08-18 18:30:30
【问题描述】:

除了 pthread_attr_t 之外,来自 POSIX 线程的 pthread_create 的所有参数都非常易于理解。 pthread_attr_t 的用途是什么,如何以及何时不应该由 NULL 初始化?

我浏览了 Linux man page。我找到的关于 pthread_attr_t 的描述是:

  • 语法:

    int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void*),void *arg);
    
  • 解释:

    The attr argument points to a pthread_attr_t structure whose contents
    are used at thread creation time to determine attributes for the new
    thread; this structure is initialized using pthread_attr_init(3) and
    related functions.  If attr is NULL, then the thread is created with
    default attributes.
    

这是非常不清楚的。我还在互联网上搜索了整个互联网,也没有在任何地方找到明确的解释。那么,当 pthread_attr_t 不是 NULL 时?

有人可以解释一下吗?非常感谢所有 cmets 和反馈。

【问题讨论】:

    标签: c multithreading arguments pthreads posix


    【解决方案1】:

    您可以使用它来创建分离的(不可连接的)线程,或者将线程的堆栈大小设置为非默认值,以及其他属性。

    请参阅 POSIX 规范:

    (每个 URL 有两个函数——pthread_attr_destroy() 和类似于“set”函数的“get”。)

    大多数情况下,您不需要修改这些。将 NULL 指针传递给 pthread_create() 等效于使用一组默认属性——这是 pthread_attr_init() 为您创建的。您可以通过函数在pthread_attr_t 对象中更改您希望更改的属性,然后将修改后的对象传递给pthread_create()

    另一件事也没有明显的理由,是来自pthread_createpthread_t 数据类型定义的第一个参数。

    所有 POSIX 线程类型都是不透明的——这是 POSIX 委员会经过深思熟虑的设计决定。您不能在便携式类型中四处寻找。这使得实现更容易——你只能做函数允许你做的事情。最终,它也简化了程序员(用户)的生活;您不会被欺骗使用不会迁移到其他系统的 POSIX 实现的内部知识。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 2020-11-21
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 2018-03-13
    • 2016-12-11
    相关资源
    最近更新 更多