创建文件pthread.c
开头提要
注意编译需要链接动态库libpthread.a或者libpthread.so
命令:gcc pthread.c -o test -lpthread -g
restrict是c99标准引入的,它只可以用于限定和约束指针,并表明指针是访问一个数据对象的唯一且初始的方式.即它告诉编译器,所有修改该指针所指向内存中内容的操作都必须通过该指针来修改
1.头文件与函数
头文件:#include<pthread.h>
pthread_t //unsigned long int
pthread_attr_t //控制线程结构体类型
线程创建函数
int pthread_create(pthread_t *thread,const pthread_attr_t *attr, void*(*start_routine)(void*), void * arg);
返回值
若成功则返回0,否则返回出错编号(EAGAIN-线程数量到达上限;EINVAL-线程非法)
参数
第一个参数为指向线程标识符的指针。
第二个参数用来设置线程属性。
第三个参数是资源分配成功后,线程里运行的单元。
最后一个参数是运行函数的传入参数。
pth_join()函数
int pthread_join(pthread_t thread, void **retval); //用来等待一个线程运行结束,
参数
第一个参数是进程(pthread_create创建的进程)标识符
第二个参数是用户定义的指针,用来存储被等待线程的返回值,即pth_exit设置参数结束后,这个参数会传到pth_join的第二个参数。
返回值
0代表成功。 失败,返回的则是错误号。
pth_exit函数
唯一的参数是函数返回值,可以被pth_join函数第二个参数捕获
概括
pthread_join用于等待一个线程的结束,也就是主线程中要是加了这段代码,就会在加代码的位置卡主,直到这个线程执行完毕才往下走。
pthread_exit用于强制退出一个线程(非执行完毕退出),一般用于线程内部。
2.测试代码
#include<stdio.h>
#include<pthread.h>
static int run=1; //the status of process
static int retvalue; //the return value of process
void *start_routine(void *arg) //the function of pcocess handle
{
int *running=arg;
printf("the sum process initial,value get in is:%d\n",*running);
while(*running)
{
printf("the sub process is running!\n");
usleep(1);
}
printf("the sub process is exit!\n");
retvalue=8; //set the exit value
pthread_exit( (void*)&retvalue);
}
int main()
{
pthread_t pt;
int ret=-1;
int times=3;
int i=0;
int *ret_join=NULL;
ret=pthread_create(&pt,NULL,(void*)start_routine,&run);
if(ret!=0)
{
printf("create process failed!");
return 1;
}
usleep(1);
for(;i<times;i++)
{
printf("the main process print!\n");
usleep(1);
}
run=0;
pthread_join(pt,(void*)&ret_join);
printf("the value of process return is:%d\n",*ret_join);
return 0;
}
3.测试结果
两次测试的结果会不一样,因为main函数的进程和新建立的进程会争夺cpu资源