面试题答案
一键面试#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;
}
- 结构体定义:定义了一个复杂的结构体
struct complex_data
,包含一个整型id
,一个双精度数组data_array
和一个嵌套结构体sub_struct
。 - 线程函数:
thread_function1
计算data_array
数组元素的总和并打印。thread_function2
打印嵌套结构体中的name
和score
。
- 主线程:
- 初始化
struct complex_data
结构体变量data
。 - 创建两个线程
thread1
和thread2
,分别传入data
结构体的指针作为参数。 - 使用
pthread_join
等待两个线程结束,确保资源回收。
- 初始化
- 死锁预防:在此简单示例中,因为线程没有共享可写资源,所以不存在死锁风险。若有共享资源,可通过合理的锁机制(如
pthread_mutex_t
)来预防死锁,例如:- 确保锁的获取顺序一致,避免循环获取锁。
- 使用锁的超时机制,避免无限等待。
以上代码在简单的多线程环境中实现了结构体参数传递和不同的计算,同时考虑了线程创建、参数传递及资源回收。