C语言多线程程序中100万整数数组传递问题求助及代码调试
Hey there! Let's work through your code issues step by step—you’re already pretty close to getting this multi-threaded array sum working correctly.
Let's break down the problems in your code and refactor it to work properly:
1. Fix the Global Array Initialization Syntax Error
Your current global array initialization is invalid C syntax—global variables can only be initialized with constant expressions, not loops. We need to declare the array globally, then populate it inside the main function (and add a random seed so you get different values each run):
// Declare the array globally (no inline initialization) int table[1000000]; int main() { // Set random seed to ensure unique values on each run srand(time(NULL)); // Populate the array in main for(int i=0; i<1000000;i++){ table[i]=(rand() %10) + 1; } // ... rest of your main logic }
2. Optimize Thread Parameter Passing (Optional but More Robust)
While using a global array works, it's better practice to avoid global variables for modularity. We can define a struct to pass all necessary data to each thread, including the array pointer, segment start index, and segment length.
Full Refactored Code
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <time.h> // Struct to hold all data a thread needs typedef struct { int* arr; // Pointer to the full array int start_index; // Start position of the thread's segment int segment_size; // Number of elements in the segment int local_sum; // Store the calculated segment sum here } ThreadData; void* summary(void* arg){ ThreadData* data = (ThreadData*)arg; int sum = 0; for (int j = 0; j < data->segment_size; j++) { sum += data->arr[data->start_index + j]; } data->local_sum = sum; printf("Local sum: %d\n", sum); pthread_exit(arg); } int main(){ // Dynamically allocate the array (avoids stack overflow for large sizes) int* table = malloc(1000000 * sizeof(int)); if (!table) { perror("Failed to allocate array memory"); return 1; } // Populate the array with random values srand(time(NULL)); for(int i=0; i<1000000;i++){ table[i]=(rand() %10) + 1; } pthread_t threads[4]; ThreadData* thread_data[4]; const int segment_length = 250000; // Create 4 worker threads for (int i = 0; i < 4; i++) { thread_data[i] = malloc(sizeof(ThreadData)); if (!thread_data[i]) { perror("Failed to allocate thread data"); return 1; } thread_data[i]->arr = table; thread_data[i]->start_index = i * segment_length; thread_data[i]->segment_size = segment_length; if (pthread_create(&threads[i], NULL, summary, thread_data[i]) != 0) { perror("Failed to create thread"); return 1; } } // Wait for threads to finish and calculate global sum int global_sum = 0; for (int i = 0; i < 4; i++) { ThreadData* result; if (pthread_join(threads[i], (void**)&result) != 0) { perror("Failed to join thread"); return 1; } global_sum += result->local_sum; free(result); // Clean up thread data memory } printf("Global sum: %d\n", global_sum); free(table); // Clean up array memory return 0; }
Key Improvements Explained
- Fixed compilation errors: Corrected the global array initialization and added missing
time.hfor random seed generation - Eliminated global variables: Used a struct to pass all necessary data to threads, making the code more modular and reusable
- Added error checking: Added checks for memory allocation and thread creation failures to avoid crashes
- Dynamic array allocation: Avoids potential stack overflow from large static arrays
内容的提问来源于stack exchange,提问作者Άγγελος Μιχάλης Βύρλιος

