创建线程:pthread_creat() 函数介绍
语法 :
int pthread_creat(pthread_t *thread,
const pthread_attr_t *attr,
void *(*thread_routine)(void *),
void *arg)
参数介绍:
pthread_t thread : pthread_t 表示线程的数据类型,实际上是void * 类型。 每一个pthread_t 的变量都可以表示一个线程。
const pthread_attr attr:* 手动设置线程的属性,比如线程调用策略,所用栈内存大小等。
thread_routine: 设置开启线程之后线程需要执行的函数。 可以只有一个参数或者没有。返回值和形参都是void*类型。
*arg: 指传递给thread_routine() 函数的实参,如果thread_routine 不需要任何参数是,arg设置为NULL.
返回值介绍: 如果pthread_creat() 函数成功创建线程时,返回数字0, 否则返回非0值。具体如下:
EAGAIN: 系统资源不足,无法提供创建线程所需的资源。
EINVAL: 传递的attr 参数无效。
举例说明
#include <stdio.h>
#include <pthread.h> //pthread_creat() 需要该头文件
#include <unistd.h> //sleep() 函数需要该头文件
void * _ThreadFuncLoop(void * arg)
{
if(arg==NULL)
printf("arg is null \n");
else
printf("function:%s arg=%s\n",__FUNCTION__,(char*)arg);
}
int main()
{
pthread_t threadT1,threadT2;
char *threadPra="only for test \n";
int res=0;
/*-------cread thread1 test---------*/
printf("will test thread1 in function:%s,line:%d\n",__FUNCTION__,__LINE__);
res=pthread_creat(&threadT1,NULL,_ThreadFuncLoop,NULL);
if(res!=0)
{
printf("cread thread1 error!\n");
return -1;
}
sleep(10); //only for wait child thread.
/*-------cread thread2 test---------*/
printf("will test thread2 in function:%s,line:%d\n",__FUNCTION__,__LINE__);
res=pthread_creat(&threadT2,NULL,_ThreadFuncLoop,(void*)threadPra);
if(res!=0)
{
printf("cread thread2 error!\n");
return -1;
}
sleep(20);
return 1;
}
其它说明:
- pthread_creat() 函数定义在pthread.h 中
- pthread_creat() 创建成功之后,创建的新的子线程会立马执行用户设定的thread_routine() 函数。
- pthread_attr 属性一般不设置,使用默认配置。