什么时候pthread_attr_t不是NULL?

除了pthread_attr_t之外,来自POSIX线程的pthread_create的所有参数都非常简单易懂。 pthread_attr_t是什么,如何以及何时不应该被NULL初始化?

我浏览了Linux 手册页 。 我发现有关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时

有人可以对此有所了解吗? 所有评论和反馈都非常感谢。

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

请参阅POSIX规范:

  • pthread_attr_init()
  • pthread_attr_setdetachstate()
  • pthread_attr_setguardsize()
  • pthread_attr_setinheritsched()
  • pthread_attr_setschedparam()
  • pthread_attr_setschedpolicy()
  • pthread_attr_setscope()
  • pthread_attr_setstack()
  • pthread_attr_setstacksize()

(每个URL有两个函数 – pthread_attr_destroy()和’get’类似于’set’函数。)

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

另一个没有明显理由的事情是pthread_createpthread_t数据类型定义的第一个参数。

所有POSIX线程类型都是不透明的 – 这是POSIX委员会经过深思熟虑的设计决策。 你不能在这种类型内移动。 这使得实现更容易 – 您只能执行function允许您执行的操作。 最终,它也简化了程序员(用户)的生活; 你不会被欺骗使用不会迁移到其他系统的POSIX实现的内部知识。