4. API 比较细节 |
在POSIX.4a (1003.4a) 说明中定义线索函数。这些函数是标准的,并且相似于那些在Solaris中提供的线索实现。从Solaris到pthreads的改变是微小的,大多数情况是将thr_前缀改成pthread_。
#include <thread.h>
int thr_create (void * stkaddr, size_t stksize, void *(*func) (void *), (void *arg), long flags, thread_t *tid)
#include <pthread.h>
int pthread_create (pthread_t *tid, pthread_attr_t *attr, void *(*func) (void *), void *arg);
使用属性对象来说明创建新线索所处的状态,是Solaris和pthreads线索创建接口的之间主要的差别。通常初始化属性,然后设置成反映所需的线索状态。当创建线索时,引用带有所要求状态说明的属性对象。
在下面的例子中,为每一种情况初始化和设置一个新的属性对象。实际上,一组属性对象 - 对于每一所需的状态行为 - 应该建立一次,然后按照需要引用。
用缺省的堆栈和堆栈大小非绑定地、非分离地创建一个缺省线索,而且它继承父亲的优先级。用NULL属性参数创建一个线索,有与缺省属性一样的效果。二者将创建一个缺省线索。当初始化‘tattr’时,它要求缺省的行为。
pthread_attr_t tattr;
pthread_t tid;
int ret;
ret = pthread_create (&tid, NULL , func, arg); /* default behavior*/ OR
ret = pthread_attr_init (&tattr); /* initialized with default attributes */
ret = pthread_create (&tid, &tattr, func, arg); /* default behavior*/
pthread_attr_t tattr;
pthread_t tid;
int ret;
ret = pthread_attr_init (&tattr); /* initialized with default attributes */
ret = pthread_attr_setscope (&tattr, PTHREAD_SCOPE_SYSTEM ); /* BOUND behavior */ ret = pthread_create (&tid, &tattr, func, arg);
pthread_attr_t tattr;
pthread_t tid;
int ret;
ret = pthread_attr_init (&tattr); /* initialized with default attributes */
ret = pthread_attr_setdetachstate (&tattr, PTHREAD_THREAD_DETACHED );
ret = pthread_create (&tid, &tattr, func, arg);
pthread_attr_t tattr;
pthread_t tid;
int ret;
void *stackbase;
int size = PTHREAD_MIN_STACK + 0x1000;
ret = pthread_attr_init (&tattr); /* initialized with default attributes */
ret = pthread_attr_setstacksize (&tattr, size ); /* setting the size of the stack also */
ret = pthread_create (&tid, &tattr, func, arg); /* only size specified */
pthread_attr_t tattr;
pthread_t tid;
int ret;
void *stackbase;
stackbase = (void *) malloc (size);
ret = pthread_attr_init (&tattr); /* initialized with default attributes */
ret = pthread_attr_setstackaddr (&tattr, stackbase ); /* setting the base address in the attribute */
ret = pthread_create (&tid, &tattr, func, arg); /* only address specified */
pthread_attr_t tattr;
pthread_t tid;
int ret;
void *stackbase;
int size = PTHREAD_MIN_STACK + 0x1000;
stackbase = (void *) malloc (size);
ret = pthread_attr_init (&tattr); /* initialized with default attributes */
ret = pthread_attr_setstacksize (&tattr, size ); /* setting the size of the stack also */
ret = pthread_attr_setstackaddr (&tattr, stackbase ); /* setting the base address in the attribute */
ret = pthread_create (&tid, &tattr, func, arg); /*address and size specified */
Copyright: NPACT |