Linux系统编程之循环创建N个子线程并顺序输出实现教程,linux个子
实现代码
代码很简单,如下。但是也有坑!在给线程传参数的不能穿 循环遍历i 的 地址,因为 i 在主线程中 ,被多个线程共享,所以不是唯一的。那么如何让每个线程 都有独自拥有自己的顺序编号呢?
1.方法一:当然可以在堆上开辟空间存储顺序编号呗。自己有自己的顺序编号的空间各自独立。
2.方法二:就是参数是void* 可以直接将循环变量i直接传给void* ,由于 arg 是每个线程 栈空间上的变量 故此 属于各个子线程,然后在使用的时候强转回 int,因为void* 和 int 刚好 都是4字节,这样做是安全的。
#include #include #include #include //线程 回调函数
void* myfun(void* arg)
{
//int num = (int)arg;//利用值传递的方式,因为void* 和 int类型 刚好都是4个字节所有可以进行强转
int num = *((int*)arg);
sleep(num);
printf("[%d] child thread id %lu\n",num,pthread_self());
return NULL;
}
int main(void)
{
pthread_t pthid[5];
int i;
for(i = 0;i< 5 ; i++)
{
int* temp = (int*)malloc(sizeof(int));
*temp = i;
pthread_create(&pthid[i],NULL,myfun,(void*)temp);
//pthread_create(&pthid[i],NULL,myfun,(void*)i);//可以通过值传递的方式,每个线程都自己的栈空间 保存着各种的顺序
}
sleep(i);//让线程按顺序进程打印
printf("parent thread id %lu\n",pthread_self());
return 0;
}
实现效果:
http://www.dengb.com/Linuxjc/1314979.htmlwww.dengb.comtruehttp://www.dengb.com/Linuxjc/1314979.htmlTechArticleLinux系统编程之循环创建N个子线程并顺序输出实现教程,linux个子 实现代码 代码很简单,如下。但是也有坑!在给线程传参数的不能穿 循...