int pthread_create(pthread_t*restrict tidp,const pthread_attr_t *restrict_attr,void*(*start_rtn)(void*),void *restrict arg);
对于linux下创建线程的方式,大家应该并不陌生,接下来我们来看下pthread_create的第四个参数,它是传入线程函数的参数,在我们在用循环语句创建多个线程时来传入这个参数,这就有些问题要注意了,如下程序
#include
#include
void* threadFunc(void* param){
unsigned num = *(unsigned*)param;
printf("threadID %u , num = %u\n",pthread_self(),num);
return NULL;
}
int main()
{
pthread_t threadID[5];
unsigned i=0;
for(i=0;i<5;i++){
pthread_create(threadID+i,NULL,threadFunc,&i);
printf("create NO.%u pthread success!,pthreadID is %u\n",i,threadID[i]);
}
for(i=0;i<5;i++){
pthread_join(threadID[i],NULL);
}
return 0;
}
运行结果:
这个结果和我们预料的结果不一样,线程函数中竟然输出的参数值全为0(这里我认为应该全为4才对,如果哪位知道这个地方为什么全为0的话,麻烦告诉一下啦lj151651605@http://www.doczj.com/doc/9bfdc79edaef5ef7ba0d3c1e.html),这里要说明的是,pthread_create创建完线程之后,会立即返回,直接执行主线程中下面的语句,根据输出结果的显示,主线程全部执行完之后,再执行线程函数的,这样传入的i值应该都为4了,解决这个问题的方式应该要保护这个传入i值的正确性。
解决方案共四种:
1.声明一个数组来存储i的值(注意这个数组的作用域) 推荐
2.动态创建空间来存储i的值推荐
3.信号量来控保护i的正确传入