c:pthreads:parallel-increment-vector
This is an old revision of the document!
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 // Numărul de thread-uri #define VECTOR_SIZE 100 // Dimensiunea vectorului // Structura pentru a stoca informațiile pentru fiecare thread typedef struct { int start; // Indexul de început pentru acest thread int end; // Indexul de sfârșit pentru acest thread int *vector; // Pointer către vector } ThreadData; // Funcția executată de fiecare thread void *increment_vector(void *arg) { ThreadData *data = (ThreadData *)arg; 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; // Inițializează vectorul for (int i = 0; i < VECTOR_SIZE; i++) { vector[i] = i; } // Creează thread-urile 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]); } // Așteaptă ca thread-urile să termine for (int i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } // Afișează vectorul incrementat for (int i = 0; i < VECTOR_SIZE; i++) { printf("%d\n", vector[i]); } return 0; }
c/pthreads/parallel-increment-vector.1705441912.txt.gz · Last modified: 2024/01/16 23:51 by odefta