子线程与父线程的简单使用
以及通过一个结构体达到传值的效果
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
typedef struct {
int a;
char b;
char str[10];
}exit_t; //返回值为一个结构体
void *ftn( void *arg )
{
int s;
exit_t *retval; //retval的地址在栈空间,但是retval本身却位与堆空间(heap),malloc所分配的。
retval=(exit_t *)malloc( sizeof(exit_t) ); //必须用malloc分配,不能用线程栈空间
s=(int)arg; //注意只能传值,不能传地址(用于判别是哪个线程)
if( s<=1 )
{
retval->a=10;
retval->b='a';
strcpy(retval->str,"zsx");
}
if( s>1 && s<=3 )
{
retval->a=20;
retval->b='b';
strcpy(retval->str,"rgf");
}
if( s>3 )
{
retval->a=30;
retval->b='c';
strcpy(retval->str,"zy");
}
printf("I am %dth thread, and my ID is %lu.\n",s+1,pthread_self( ));
pthread_exit((void *)retval); //或者 return (void *)retval; 两者等价!
}
int main(int argc, char *argv[ ])
{
int n=5, i, ret;
if( argc==2 )
n=atoi(argv[1]);
pthread_t tid[n];
for(i=0;i<n;i++)
{
ret=pthread_create(&tid[i],NULL,ftn,(void *)i); //注意只能传值,不能传地址,因为地址对应的i值会变化
if( ret!=0)
{
fprintf(stderr,"pthread_create error: %s\n",strerror(ret));
exit(1);
}
}
for(i=0;i<n;i++) //回收每个子线程
{
//子线程给主线程传的值 放于此处
exit_t *re; //re位于主控线程的栈空间,但是re本身的值为子线程传给它的值。
ret=pthread_join( tid[i],(void **)&re);
if( ret!=0)
{
fprintf(stderr,"pthread_join error: %s\n",strerror(ret));
exit(1);
}
printf("the %dth thread: a=%d, b=%c, str=%s.\n",i+1,re->a,re->b,re->str);
free(re); //注意必须释放malloc分配的空间,防止内存泄漏
re = NULL; //置空,防止使用幽灵指针
}
printf("In main: the PID is %d, and the TID is %lu.\n",getpid( ),pthread_self( ));
pthread_exit((void *)1);
}
于是发现一个很好玩的结果:
运行结果如下:
线程是从 5-1执行的
在for循环中,pthread_create函数后面加入
sleep(1);
运行结果变成如下:
线程是从 1-5执行
为什么会有这样的不同结果呢?
日后再研究。
2020/6/24 23:20