2017-03-25 22 views
0

从POSIX线程的pthread_create的所有参数都非常直截了当,除了pthread_attr_t。什么是pthread_attr_t的,怎么样,当它应该是不被NULL初始化?当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

有人可以请说一说吗?所有评论和反馈都非常感谢。

回答

4

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

见POSIX规范:

(有每个URL两个功能 - pthread_attr_destroy()和 '得到' 类似物的 '设置' 功能)

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

另一件没有明显理由的数据类型定义是pthread_create的第一个参数pthread_t

所有的POSIX线程类型都是不透明的 - 这是POSIX委员会的故意设计决定。你不能在可移植类型内部徘徊。这使得实现更容易 - 只能执行功能允许的功能。最终,它也简化了程序员(用户)的生活;你不会被欺骗使用POSIX实现的内部知识,而这些知识不会迁移到其他系统。

+0

非常感谢你的启发性答案。你提到:“创建一个分离(不可连接)的线程”...然后我遵循你的建议,并找到这个例子:http://stackoverflow.com/questions/6202762/pthread-create-as-detach ed和还发现更多的为什么或何时有线程分离:http://stackoverflow.com/questions/3756882/detached-vs-joinable-posix-threads。谢谢! –