Increment elements of a vector in parallel using pthreads
Parallelize the incrementing of elements in a 100-element array. This will involve dividing the addition iteration among all threads in the most equitable way possible.
- increment-vector-parallel.c
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define NUM_THREADS 4 // Number of threads to use #define VECTOR_SIZE 100 // Size of the array // Structure to pass information to threads typedef struct { int start; // Starting index for this thread int end; // Ending index for this thread int *vector; // Pointer to the array } ThreadData; // Function that each thread will execute void *increment_vector(void *arg) { ThreadData *data = (ThreadData *)arg; // Increment the array elements in the specified range for (int i = data->start; i < data->end; i++) { data->vector[i]++; } pthread_exit(NULL); } int main() { int vector[VECTOR_SIZE]; pthread_t threads[NUM_THREADS]; ThreadData thread_data[NUM_THREADS]; int segment_size = VECTOR_SIZE / NUM_THREADS; // Initialize the array for (int i = 0; i < VECTOR_SIZE; i++) { vector[i] = i; } // Create threads and assign them segments of the array for (int i = 0; i < NUM_THREADS; i++) { thread_data[i].start = i * segment_size; thread_data[i].end = (i == NUM_THREADS - 1) ? VECTOR_SIZE : (i + 1) * segment_size; thread_data[i].vector = vector; pthread_create(&threads[i], NULL, increment_vector, (void *)&thread_data[i]); } // Wait for all threads to complete for (int i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } // Display the incremented array for (int i = 0; i < VECTOR_SIZE; i++) { printf("%d\n", vector[i]); } return 0; }
The process involves splitting the array into nearly equal segments and assigning each segment to a different thread for incrementing.
Define an Array and Thread Information: First, define a 100-element array and decide on the number of threads. The array will be split into segments, with each segment processed by a different thread.
Thread Function: Write a function that each thread will execute. This function should accept a range of indices to process (start and end indices) and increment the elements within this range.
Create and Initialize Threads: Create threads and pass them their respective array segments to process. Ensure the segments cover the entire array and are as evenly distributed as possible.
Wait for Threads to Complete: After starting all threads, use pthread_join to wait for all threads to finish their execution.
Finalize: Optionally, after all threads have completed, you can perform any final processing or output the updated array.
This method efficiently utilizes multiple cores (if available) to perform the increment operation in parallel, potentially reducing the total processing time compared to a single-threaded approach. It's important in such parallel operations to carefully manage thread creation and synchronization to avoid issues like race conditions.