MST

星途 面试题库

面试题:C语言多线程中结构体作为线程参数的复杂处理

定义一个复杂的C语言结构体 `struct complex_data { int id; double data_array[10]; struct { char name[20]; float score; } sub_struct; };`,现在要将这个结构体作为参数传递给多个线程函数,每个线程根据结构体中的数据进行不同的计算。要求编写代码实现这个过程,并处理好线程的创建、参数传递以及线程结束后的资源回收,同时要考虑到多线程编程中的常见问题如死锁预防等。
37.8万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

// 定义复杂结构体
struct complex_data {
    int id;
    double data_array[10];
    struct {
        char name[20];
        float score;
    } sub_struct;
};

// 线程函数1
void* thread_function1(void* arg) {
    struct complex_data* data = (struct complex_data*)arg;
    // 在此处根据结构体数据进行计算
    double sum = 0;
    for (int i = 0; i < 10; i++) {
        sum += data->data_array[i];
    }
    printf("Thread 1: Sum of data_array for id %d is %lf\n", data->id, sum);
    return NULL;
}

// 线程函数2
void* thread_function2(void* arg) {
    struct complex_data* data = (struct complex_data*)arg;
    // 在此处根据结构体数据进行计算
    printf("Thread 2: Name %s has score %f\n", data->sub_struct.name, data->sub_struct.score);
    return NULL;
}

int main() {
    struct complex_data data = {
       .id = 1,
       .data_array = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10},
       .sub_struct = {
           .name = "John",
           .score = 85.5f
        }
    };

    pthread_t thread1, thread2;

    // 创建线程1
    if (pthread_create(&thread1, NULL, thread_function1, &data) != 0) {
        perror("Failed to create thread 1");
        return 1;
    }

    // 创建线程2
    if (pthread_create(&thread2, NULL, thread_function2, &data) != 0) {
        perror("Failed to create thread 2");
        pthread_cancel(thread1);
        return 1;
    }

    // 等待线程1结束
    if (pthread_join(thread1, NULL) != 0) {
        perror("Failed to join thread 1");
        pthread_cancel(thread2);
        return 1;
    }

    // 等待线程2结束
    if (pthread_join(thread2, NULL) != 0) {
        perror("Failed to join thread 2");
        return 1;
    }

    return 0;
}
  1. 结构体定义:定义了一个复杂的结构体struct complex_data,包含一个整型id,一个双精度数组data_array和一个嵌套结构体sub_struct
  2. 线程函数
    • thread_function1计算data_array数组元素的总和并打印。
    • thread_function2打印嵌套结构体中的namescore
  3. 主线程
    • 初始化struct complex_data结构体变量data
    • 创建两个线程thread1thread2,分别传入data结构体的指针作为参数。
    • 使用pthread_join等待两个线程结束,确保资源回收。
  4. 死锁预防:在此简单示例中,因为线程没有共享可写资源,所以不存在死锁风险。若有共享资源,可通过合理的锁机制(如pthread_mutex_t)来预防死锁,例如:
    • 确保锁的获取顺序一致,避免循环获取锁。
    • 使用锁的超时机制,避免无限等待。

以上代码在简单的多线程环境中实现了结构体参数传递和不同的计算,同时考虑了线程创建、参数传递及资源回收。