线程参数传递 同一个结构体指针,并且要传递id(0-xx)的方法

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

提示:这里可以添加本文要记录的大概内容:

线程参数传递 同一个结构体指针,并且要传递id(0-xx)的方法
在创建线程时候可能会遇到不仅要传递 全局唯一的结构体指针给线程,还需要传递创建线程的id(0-xx)给线程,线程的arg只能传递一个参数,

可以再构建结构体,然后malloc然后在线程中使用完成后free


提示:以下是本篇文章正文内容,下面案例可供参考

一、代码示例?

示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>


typedef struct {
    long id;
    char name[16];
}  my_st;


// 线程函数
void* thread_function(void* arg) {
    long Id = ((my_st *)arg)->id;
    char c = ((my_st *)arg)->name[0];
    printf("Hello from id = %ld, c = %c\n", Id, c);
    free(arg); //线程内部使用完成后free
    pthread_exit(NULL);
}

int main() {
    // 定义线程 ID 数组
    pthread_t threads[10];
    int rc;
    char c = 'c';

    // 创建 10 个线程
    for (long i = 0; i < 10; i++) {
        //rc = pthread_create(&threads[i], NULL, thread_function, (void *)i); // 传递值 直接正常
        my_st* p_st = malloc(sizeof(my_st)); // 外部构建结构体malloc
        p_st->id = i;
        memset(p_st->name, c + (char)i, 1);
        rc = pthread_create(&threads[i], NULL, thread_function, p_st);// 传递指针 确保指针指向的数据不会被修改
        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;
}

总结

线程参数传递 同一个结构体指针,并且要传递id(0-xx)的方法。
可以再构建结构体,然后创建线程时malloc,然后在线程处理函数中使用完成后free

  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值