linux 线程传参注意事项

场景:

提示:这里简述项目相关背景:

创建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传递的地址

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值