目录
2.2 关心线程收回的退出状态。用到----线程退出 pthread_exit( )
1.线程创建:pthread_create( )
-
int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
-
// 返回:若成功返回0,否则返回错误编号
#include <stdio.h>
#include <pthread.h>
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr,
// void *(*start_rtn)(void *), void *restrict arg);
void *func1(void *arg)
{
printf("%ld thread is create\n",(unsigned long)pthread_self()); //打印线程的pid
printf("param is %d\n",*((int *)arg));
}
int main()
{
int ret;
pthread_t t1; /*不使用指针是以免空指针异常*/
int arg = 100;
//创建 t1 线程
ret = pthread_create(&t1,NULL,func1,(void *)&arg); //参数2:线程属性,一般设置为NULL,参数3:线程干活的函数,参数4:往t1线程里面传送数据。
//ret = pthread_create(&t1,NULL,func1,NULL);
if(ret == 0){
printf("create t1 success\n");
}
return 0;
}
由运行结果可以看出:
t1 线程还没有执行完,主线程就已经运行完毕。
所以要看到 t1 线程的运行,要么加在主线程加一个 while(1) 死循环。要么用到线程的等待函数 pthread_join( )。请看下面。
2.线程等待:pthread_join( );
-
int pthread_join(pthread_t thread, void **rval_ptr);
-
// 返回:若成功返回0,否则返回错误编号
-
第 2 个参数,可以设置为NULL不关心线程收回的退出状态
2.1 第2个参数设为NULL,不关心线程收回的退出状态
#include <stdio.h>
#include <pthread.h>
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr,
// void *(*start_rtn)(void *), void *restrict arg);
//nt pthread_join(pthread_t thread, void **rval_ptr);
void *func1(void *arg)
{
printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
printf("t1:param is %d\n",*((int *)arg));
}
int main()
{
int ret;
pthread_t t1;
int arg = 100;
//创建线程
ret = pthread_create(&t1,NULL,func1,(void *)&arg);
if(ret == 0){
printf("main:create t1 success\n");
}
printf("main:%ld \n",(unsigned long)pthread_self());
//线程等待/阻塞
pthread_join(t1,NULL);
return 0;
}
2.2 关心线程收回的退出状态。用到----线程退出 pthread_exit( )
int pthread_exit(void *rval_ptr);
#include <stdio.h>
#include <pthread.h>
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr,
// void *(*start_rtn)(void *), void *restrict arg);
//nt pthread_join(pthread_t thread, void **rval_ptr);
void *func1(void *arg)
{
static char *p = "t1 is run out"; //变量必须定义前加 static ,否则二级指针指向它的时候数据会出错
printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
printf("t1:param is %d\n",*((int *)arg));
pthread_exit((void *)p); //线程退出,并且返回 p 指向的字符串
}
int main()
{
int ret;
pthread_t t1;
int arg = 100;
char *pret = NULL; //不可以直接定义为二级指针
//创建线程
ret = pthread_create(&t1,NULL,func1,(void *)&arg);
if(ret == 0){
printf("main:create t1 success\n");
}
printf("main:%ld \n",(unsigned long)pthread_self());
//线程的等待/阻塞
pthread_join(t1,(void **)&pret); //参数2:将指针pret 指向 t1线程的p
printf("main: t1 quit :%s\n",pret);
return 0;
}