场景:
提示:这里简述项目相关背景:
创建10个线程,每个线程中打印创建的id
问题描述
提示:这里描述项目中遇到的问题:
给线程参数直接传 地址,然后在线程中接收数据,会导致传入的值arg值可能被改变,从而使程序异常。
给线程参数直接传 数据,能够正常。
创建10个线程打印 0 - 9:
正常:0 - 9 都能打印一次
异常:0 - 9有些数没打印,有些打印多次
问题代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// 线程函数
void* thread_function(void* arg) {
long Id = *((long *)arg);
printf("Hello from id = %ld\n", Id);
pthread_exit(NULL);
}
int main() {
// 定义线程 ID 数组
pthread_t threads[10];
int rc;
// 创建 10 个线程
for (long i = 0; i < 10; i++) {
//rc = pthread_create(&threads[i], NULL, thread_function, (void *)i);
rc = pthread_create(&threads[i], NULL, thread_function, &i);
if (rc) {
printf("Error: unable to create thread, error code = %d\n", rc);
exit(-1);
}
}
// 等待所有线程完成
for (long i = 0; i < 10; i++) {
rc = pthread_join(threads[i], NULL);
if (rc) {
printf("Error: unable to join, error code = %d\n", rc);
exit(-1);
}
}
printf("Main: program exiting.\n");
return 0;
}
运行结果:打印数据错误乱
正常代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// 线程函数
void* thread_function(void* arg) {
long Id = *((long *)arg);
printf("Hello from id = %ld\n", Id);
pthread_exit(NULL);
}
int main() {
// 定义线程 ID 数组
pthread_t threads[10];
int rc;
// 创建 10 个线程
for (long i = 0; i < 10; i++) {
rc = pthread_create(&threads[i], NULL, thread_function, (void *)i);
//rc = pthread_create(&threads[i], NULL, thread_function, &i);
if (rc) {
printf("Error: unable to create thread, error code = %d\n", rc);
exit(-1);
}
}
// 等待所有线程完成
for (long i = 0; i < 10; i++) {
rc = pthread_join(threads[i], NULL);
if (rc) {
printf("Error: unable to join, error code = %d\n", rc);
exit(-1);
}
}
printf("Main: program exiting.\n");
return 0;
}
运行结果:正常打印 0 - 9
原因分析:
提示:这里填写问题的分析:
&i 传递的使 i 的地址,在线程创建后如果还未来的及运行,i就继续循环,i++后,线程再运行就会出现这种情况。(线程都是被cpu在某一时间段调度的,调度顺序可能和创建顺序不同)
解决方案:
提示:这里填写该问题的具体解决方案:
线程arg时候,如果传递地址,尽量确保所有线程的 arg都独立,线程没有执行完成不操作arg传递的地址