注:
https://blog.csdn.net/weixin_44517656/article/details/109433060
- 2)wait回收子进程并且获取正常退出的返回值和异常退出的信号值的文章:
https://blog.csdn.net/weixin_44517656/article/details/109453889
- 3)waitpid回收指定子进程并分析回收pid出错原因:
https://blog.csdn.net/weixin_44517656/article/details/109456869
https://blog.csdn.net/weixin_44517656/article/details/109479191
1 循环创建多个子线程
个人觉得比循环创建多个子进程简单多了。可能进程用得比较少的原因吧。
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
void *tfn(void *arg){
int i;
i = (int)arg;
sleep(i); //通过i来区别每个线程
printf("I'm %dth thread, Thread_ID = %lu\n", i+1, pthread_self());
return NULL;
}
int main(int argc, char *argv[]){
int n = 5, i;
pthread_t tid[n];
for (i = 0; i < n; i++) {
tid[i] = -1;
}
for (i = 0; i < n; i++) {
pthread_create(&tid[i], NULL, tfn, (void *)i);
}
for (i = 0; i < n; i++) {
if(tid[i] != -1){
pthread_join(i, NULL);
}
}
printf("I am main, and I am not a process, I'm a thread!\n"
"main_thread_ID = %lu\n", pthread_self());
return 0;
}
2 上面代码分析线程传参大坑
下面我们来分析上面代码改成这样的时候就会出错:
pthread_create(&tid[i], NULL, tfn, (void *)&i);//将i改成&i
上面代码会有问题,根本原因是多线程同时操作一个变量。主线程在写(自增i++),子线程在读。所以数据根本不会同步,需要加上锁。
当然也可以使用图来解释:可以看到,子线程不断读主线程中i的地址,但是主线程又不断写入新值的i,这样执行程序就会出现i比1大或者出现无穷大(小)的数。
解决:所以我们需要值传递,直接看第1点强转即可。