POSIX 之线程、线程属性(pthread attr)

POSIX 之线程、线程属性(pthread attr)

0 引言

本文主要介绍posix标准中线程以及线程属性的相关内容,但是posix标准在不同平台下的实现并不完全一致,本文主要介绍pthread系列API的基本使用同时介绍在不同平台(Linux—Ubuntu18.04 64位 和VxWorks 6.8)下的实现差异.博文的主要内容由以下几个方面组成:

  • posix线程的使用(Linux)
  • posix线程Linux和VxWorks的差异
  • posix线程属性pthread_attr详解(Linux)
  • pthread_attr Linux和VxWorks下差异

1 posix 线程管理

1.1 API 总览

Thread management APIs allow a program manipulate threads. The APIs actually create, destroy and otherwise manage the active or ended threads within the application. The APIs allow the manipulation of some of the thread attributes of an active thread.

函数 描述 Linux VxWorks 备注
pthread_create() Create a Thread suport suport
pthread_clear_exit_np() Clear the Exit Status of a Thread suport suport
pthread_create() Create a Thread suport suport
pthread_delay_np() Delay a Thread for the Requested Interval suport suport
pthread_detach() Detach a Thread suport suport
pthread_equal() Compare Two Threads suport suport
pthread_exit() Terminate The Calling Thread suport suport
pthread_extendedjoin_np() Wait for a Thread with Extended Options suport suport
pthread_getconcurrency() Get the Process Concurrency Level suport suport
pthread_getpthreadoption_np() Get Pthread Run-Time Option Data suport suport
pthread_getschedparam() Get Thread Scheduling Parameters suport suport
pthread_getthreadid_np() Retrieve a Unique Id for the Calling Thread suport suport
pthread_getunique_np() Retrieve a Unique Id for the Target Thread suport suport
pthread_is_multithreaded_np() Check the Current Number of Threads suport suport
pthread_join() Wait for and Detach a Thread suport suport
pthread_join_np() Wait for a Thread to End suport suport
pthread_once() Perform One Time Initialization suport suport
pthread_self() Get Pthread Handle suport suport
pthread_setconcurrency() Set The Process Concurrency Level suport suport
pthread_setpthreadoption_np() Set Pthread Run-Time Option Data suport suport
pthread_setschedparam() Set Target Thread Scheduling Parameters suport suport
sched_yield() Yield the Processor to Another Thread suport suport

以上主要是线程管理相关的接口,本文病没有 详细介绍每个函数的用法,感兴趣的同学可以依次进行查阅相关的man手册,或者 pthreads Management 相关用法

1.2 API 详解

1.2.1 pthread_create()

1.2.2 未完。。。。。。。

2 线程属性

2.1 线程属性结构体

POSIX标准只是定义pthread_arrt_t结构体的相关标准,不同的平台定义的具体略微不同

bits\pthreadtypes.h
typedef union
{
  char __size[__SIZEOF_PTHREAD_ATTR_T];
  long int __align;
} pthread_attr_t;

在Linux平台下该结构体通常为:

typedef struct
{      
  int	detachstate;       //线程的分离状态
  int schedpolicy;    //线程调度策略
  struct sched_param schedparam;  //线程的调度參数
  int inheritsched;     //线程的继承性
  int scope;         //线程的作用域
  size_t  guardsize;     //线程栈末尾的警戒缓冲区大小
  void* stackaddr;      //线程栈的位置
  size_t  stacksize;        //线程栈的大小
}pthread_attr_t;

而在VxWorks平台则增加了两项:pthread name and pthread options

typedef struct
{
      int    threadAttrStatus;			/* status flag              */
      size_t threadAttrStacksize;		/* stack size               */
      void * threadAttrStackaddr;		/* stack address            */
      size_t threadAttrGuardsize;		/* guard address (RTP only) */
      int    threadAttrDetachstate;		/* detach state             */
      int    threadAttrContentionscope;		/* contention scope         */
      int    threadAttrInheritsched;		/* inherit scheduler        */
      int    threadAttrSchedpolicy;		/* scheduling policy        */
      char * threadAttrName;		/* task name - VxWorks extension    */
      int    threadAttrOptions;		/* task options - VxWorks extension  */
      struct _Sched_param threadAttrSchedparam; /* sched param struct */
 } pthread_attr_t;

后面会对这两项进行详细地介绍

2.2 API总览

函数 描述 Linux VxWorks 备注
pthread_attr_init() Initialize a Thread Attributes Object suport suport
pthread_attr_destroy() Destroy a Thread Attributes Object suport suport
pthread_attr_getdetachstate() Get Thread Attributes Object Detachstate suport suport
pthread_attr_setdetachstate() Set Thread Attributes Object Detachstate suport suport
pthread_attr_getinheritsched() Get Thread Attribute Object Inherit Scheduling Attributes suport suport
pthread_attr_setinheritsched() Set Thread Attribute Inherit Scheduling Attributes suport suport
pthread_attr_getschedparam() Get Thread Attributes Object Scheduling Parameters suport suport
pthread_attr_setschedparam() Set Thread Attributes Object Scheduling Parameters suport suport
pthread_attr_getschedpolicy() Get Scheduling Policy suport suport
pthread_attr_setschedpolicy() Set Scheduling Policy suport suport
pthread_attr_getscope() Get Scheduling Scope suport suport
pthread_attr_setscope() Set Scheduling Scope suport suport
pthread_attr_getstackaddr() Get Stack Address suport suport
pthread_attr_setstackaddr() Set Stack Address suport suport
pthread_attr_getstacksize() Get Stack Size suport suport
pthread_attr_setstacksize() Set Stack Size suport suport
pthread_attr_getstack() Get the values of the stack address and size attributes suport suport
pthread_attr_setstack() Set the values of the stack address and size attributes suport suport

2.3 API详解

2.3.1 pthread_attr_init()

2.3.2。。。。未完待续

2.4 VxWorks有POSIX线程属性的扩展

2.4.1 VxWorks中有关pthread_attr_t 的扩展

VxWorks中每个线程都是一个任务,每个任务都有自己的名称以及以下选项,VxWorks在pthread_attr_t中扩展了这两项内容,这是因为VxWorks中任务就有两个选项,VxWorks中创建线程的API如下:

int taskSpawn (char *  name,        /* name of new task (stored at pStackBase) */
 				int     priority,    /* priority of new task */
 				int     options,     /* task option word */
			    int     stackSize,   /* size (bytes) of stack needed plus name */
			    FUNCPTR entryPt,     /* entry point of new task */
			    int     arg1,        /* 1st of 10 req'd args to pass to entryPt */
			    int     arg2,        
			    int     arg3,        
			    int     arg4,        
			    int     arg5,        
			    int     arg6,        
			    int     arg7,        
			    int     arg8,        
			    int     arg9,        
			    int     arg10);    

2.4.2 Pthread Name

Pthread Name While POSIX threads are not named
entities, the VxWorks tasks upon which they are based are named. By
default the underlying task elements are named pthrNumber (for
example, pthr3). The number part of the name is incremented each time
a new thread is created (with a roll-over at 2^32 - 1). It is,
however, possible to name these tasks using the thread name attribute.
■ Attribute Name: threadname
■ Possible Values: a null-terminated string of characters
■ Default Value: none (the default naming policy is used)
■ Access Functions (VxWorks-specific POSIX extensions)

pthread_attr_getname( )

NAME
pthread_attr_getname( ) - get name of thread attribute object 
SYNOPSIS
int pthread_attr_getname(pthread_attr_t *pAttr,char **name)                        
DESCRIPTION
This routine gets the name in the specified thread attributes object, pAttr. 
RETURNS
zero on success, EINVAL if an invalid thread attribute is passed or if name is NULL. 
ERRNO
None

pthread_attr_setname( )

扫描二维码关注公众号,回复: 9279656 查看本文章
NAME
pthread_attr_setname( ) - set name in thread attribute object 
SYNOPSIS
int pthread_attr_setname ( pthread_attr_t * pAttr,   char * name ) ;                      
DESCRIPTION
This routine sets the name in the specified thread attributes object, pAttr. 

RETURNS
zero on success, EINVAL if an invalid thread attribute is passed. 

2.4.3 Pthread Options

POSIX threads are agnostic with regard to target architecture. Some
VxWorks tasks, on the other hand, may be created with specific options
in order to benefit from certain features of the architecture. For
example, for the Altivec-capable PowerPC architecture, tasks must be
created with the VX_ALTIVEC_TASK in order to make use of the Altivec
processor. The pthread options attribute can be used to set such
options for the VxWorks task upon which the POSIX thread is based.
■Attribute Name: threadoptions
■ Possible Values: the same as the VxWorks task options. See taskLib.h
■ Default Value: none (the default task options are used)
■ Access Functions (VxWorks-specific POSIX extensions):

pthread_attr_setopt( )

NAME
pthread_attr_setopt( ) - set options in thread attribute object 
SYNOPSIS
int pthread_attr_setopt ( pthread_attr_t * pAttr, int  options)                          
DESCRIPTION
This non-POSIX routine sets options in the specified thread attributes object, pAttr. This allows for specifying a non-default set of options for the VxWorks task acting as a thread. Additional options may be applied to the task once the thread has been created via the taskOptionsSet( ) API. 
Note that the task options provided through this routine will supersede the default options otherwise applied at thread creation. 
See taskLib.h for definitions of valid task options. 
RETURNS
zero on success, EINVAL if an invalid thread attribute is passed. 
ERRNO
None. 
SEE ALSO
pthreadLib, pthread_attr_getopt( ), taskOptionsSet( ) 

pthread_attr_getopt( )

NAME
pthread_attr_getopt( ) - get options from thread attribute object 
SYNOPSIS
int pthread_attr_getopt ( pthread_attr_t * pAttr,   int *  pOptions )                           
DESCRIPTION
This non-POSIX routine gets options from the specified thread attributes object, pAttr. To see the options actually applied to the VxWorks task under thread, use taskOptionsGet(). 
This routine expects the pOptions parameter to be a valid storage space. 
See taskLib.h for definitions of task options. 
RETURNS
zero on success, EINVAL if an invalid thread attribute is passed or if pOptions is NULL. 
ERRNO
None. 
SEE ALSO
pthreadLib, pthread_attr_setopt( ), taskOptionsGet( ) 

通过查阅VxWorks文档option取以下几个值:

Bits in the options argument may be set to run with the following
modes:

VX_FP_TASK :execute with floating-point coprocessor support. A task which performs floating point operations or calls any functions which either return or take a floating point value as arguments must be created with this option. Some routines perform floating point operations internally. The VxWorks documentation for these clearly state the need to use the VX_FP_TASK option.
VX_ALTIVEC_TASK :execute with Altivec support (PowerPC only)

VX_SPE_TASK :execute with SPE support (PowerPC only)

VX_DSP_TASK :execute with DSP support (SuperH only)

VX_PRIVATE_ENV :include private environment support (see envLib).

VX_NO_STACK_FILL : do not fill the stack for use by checkStack( ).

VX_UNBREAKABLE :do not allow breakpoint debugging.

VX_NO_STACK_PROTECT :do not provide stack protection: no overflow or underflow detection, stack remains executable.

The option bits VX_DEALLOC_STACK and VX_DEALLOC_EXC_STACK are not options available for the taskSpawn( ) API. taskSpawn( ) internally
sets these option bits by default depending on the configuration of the system. Specifying these options to taskSpawn( ) results in an ERROR and the ERRNO, S_taskLib_ILLEGAL_OPTIONS, will be returned. See the definitions in taskLib.h. It is assumed that the caller passes a valid function pointer as entryPt while calling this API. No validity check for this parameter is done here.

2.4.4 示例程序

/****暂时不进行演示/

2.5 Linux中线程名称设置

Linux中线程的名字默认和主线程保持一致,这样给调试带来很大的不变,在Linux环境采用以下两种方式来设置和获取线程的名字。

2.5.1 pthread_setname_np 和 pthread_getname_np

函数原型如下:

   #define _GNU_SOURCE             /* See feature_test_macros(7) */
   #include <pthread.h>
   int pthread_setname_np(pthread_t thread, const char *name);
   int pthread_getname_np(pthread_t thread,char *name, size_t len);

详细介绍以及例子 见 man 手册

2.5.2 利用prctl()函数实现

。。。。。。

发布了67 篇原创文章 · 获赞 15 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/wanxuexiang/article/details/104358038