循环创建线程注意事项:
- 线程独享栈空间
- 进程创建线程的时候,会把相应的栈空间的值赋给线程,创建完成后线程独享栈内的值
- 在创建线程时,若连续多次创建线程,并且要将特定参数传给线程时,可能会出现地址上的旧值还未成功赋予,地址上的旧值就被新值代替。
- 所以在传递参数时,应用传值代替传参数(不推荐),或者在创建线程时等待一段时间,确保值被成功赋予
1 #include<stdio.h>
2 #include<pthread.h>
3 #include<string.h>
4 #include<unistd.h>
5 void *th_read(void *arg)
6 {
7 int i;
8 i=*((int *)arg);//将arg强转为int类型指针再取值
9 // i=(int)arg;
10 while(1){
11 printf("Th%d: pthread_tid = %lu\n",i,pthread_self());
12 sleep(6);
13 }
14 }
15
16 void main(void)
17 {
18 pthread_t tid;
19 int ret,i;
20 //循环创建多个子线程
21 for(i=0;i<6;i++){
22 ret=pthread_create(&tid,NULL,th_read,(void *)&i);//取i地址强转为void类型指针
23 if(ret!=0){
24 printf("pthread_create error:%s\n",strerror(ret));
25 }
26 sleep(1);
27 }
28 while(1);
29 }