#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MATRIX_SIZE 3
#define VECTOR_SIZE 3
#define NUM_THREADS 2
// Matrix and vector
int matrix[MATRIX_SIZE][MATRIX_SIZE];
int vector[VECTOR_SIZE];
int result[MATRIX_SIZE];
// Mutex for accessing result array
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// Function executed by each thread
void *multiply(void *arg) {
int thread_id = *((int *)arg);
int start = thread_id * (MATRIX_SIZE / NUM_THREADS);
int end = (thread_id + 1) * (MATRIX_SIZE / NUM_THREADS);
// Compute partial result
for (int i = start; i < end; ++i) {
int sum = 0;
for (int j = 0; j < MATRIX_SIZE; ++j) {
sum += matrix[i][j] * vector[j];
}
// Protect shared result array with mutex
pthread_mutex_lock(&mutex);
result[i] = sum;
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS];
// Initialize matrix and vector
printf("Matrix:\n");
for (int i = 0; i < MATRIX_SIZE; ++i) {
for (int j = 0; j < MATRIX_SIZE; ++j) {
matrix[i][j] = rand() % 10;
printf("%d ", matrix[i][j]);
}
printf("\n");
}
printf("\nVector:\n");
for (int i = 0; i < VECTOR_SIZE; ++i) {
vector[i] = rand() % 10;
printf("%d\n", vector[i]);
}
// Create threads
for (int i = 0; i < NUM_THREADS; ++i) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, multiply, &thread_ids[i]);
}
// Join threads
for (int i = 0; i < NUM_THREADS; ++i) {
pthread_join(threads[i], NULL);
}
// Print result
printf("\nResult:\n");
for (int i = 0; i < MATRIX_SIZE; ++i) {
printf("%d\n", result[i]);
}
pthread_mutex_destroy(&mutex);
return 0;
}
评论