pthread_create(线程创建)
1、头文件:#include<pthread.h>
2、函数原型:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
3、函数形参:thread:存放线程的TID(由pthread_t定义)地址;
attr:设置线程属性,一般置NULL;
start_routine:线程所要执行的函数地址;
arg:传递给线程函数的参数。
注:(1)start_routine是void *型函数,其形参也为void *型。
(2)arg:这个参数会传递给pth_arg,如果参数很多的话,可做成一个结构体,然后将结构体变量的地址传过去。若不想传递参数,可设置为NULL。
4、函数返回值:成功返回0,失败返回错误号。
5、使用示例:
注:编译时要链接线程库(libpthread.a/.so):gcc pthread create.c –lpthread
(1)arg为NULL。
(2)arg有值且为全局变量,实现所有线程共享主线程(进程)的数据段。
(3)arg有值且为局部变量,使用地址传参,在调用的函数中必须将void *arg强转为对应的数据类型。