版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
1、创建线程/等待线程结束
1、pthread_create函数
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
//功能:用于创建一个线程
//参数1:线程号
//参数2:创建线程时需要设置的属性,如果为NULL则按默认的方式进行创建
typedef union
{
char __size[__SIZEOF_PTHREAD_ATTR_T];
long int __align;
}pthread_attr_t;
//参数3:函数指针,表示线程的入口函数
//参数4::给线程的入口函数传递的参数
2、pthread_join函数
int pthread_join(pthread_t thread, void **retval);
//功能:等待线程结束
//参数1:线程号
//参数2:指针变量的地址,用于获取入口函数的返回值,如果入口函数没有返回值则设置为NULL
举例:
#include <stdio.h>
#include <pthread.h>
//线程的入口函数
void* start_run(void* arg)
{
int* num = (int*)arg;
//在线程中我们将这个参数加10并返回
*num += 10;
return num;
}
int main()
{
pthread_t pid;
//按照默认方式来执行,线程的入口函数为start_run,入口函数的参数为a
int a = 100;
pthread_create(&pid,NULL,start_run,&a);
printf("before end a = %d\n",a);
void* p = NULL;
pthread_join(pid,&p);
printf("after end a = %d\n",*(int*)p);
}
运行效果