pthread实现多线程矩阵
时间: 2023-10-07 11:04:22 浏览: 69
pthread多线程编程
下面是一个使用pthread实现多线程矩阵乘法的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX_SIZE 100
int A[MAX_SIZE][MAX_SIZE], B[MAX_SIZE][MAX_SIZE], C[MAX_SIZE][MAX_SIZE];
int N, M, K; // A[N][M], B[M][K], C[N][K]
int num_threads;
void* multiply(void* arg) {
int thread_num = *(int*)arg;
int start = thread_num * N / num_threads;
int end = (thread_num + 1) * N / num_threads;
for (int i = start; i < end; i++) {
for (int j = 0; j < K; j++) {
C[i][j] = 0;
for (int k = 0; k < M; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
pthread_exit(NULL);
}
int main(int argc, char* argv[]) {
if (argc < 4) {
printf("Usage: %s <N> <M> <K> [num_threads]\n", argv[0]);
return 1;
}
N = atoi(argv[1]);
M = atoi(argv[2]);
K = atoi(argv[3]);
if (argc >= 5) {
num_threads = atoi(argv[4]);
} else {
num_threads = 1;
}
printf("Matrix A (%d x %d):\n", N, M);
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
A[i][j] = rand() % 10;
printf("%d ", A[i][j]);
}
printf("\n");
}
printf("Matrix B (%d x %d):\n", M, K);
for (int i = 0; i < M; i++) {
for (int j = 0; j < K; j++) {
B[i][j] = rand() % 10;
printf("%d ", B[i][j]);
}
printf("\n");
}
pthread_t* threads = (pthread_t*)malloc(num_threads * sizeof(pthread_t));
int* thread_nums = (int*)malloc(num_threads * sizeof(int));
for (int i = 0; i < num_threads; i++) {
thread_nums[i] = i;
pthread_create(&threads[i], NULL, multiply, &thread_nums[i]);
}
for (int i = 0; i < num_threads; i++) {
pthread_join(threads[i], NULL);
}
printf("Matrix C (%d x %d):\n", N, K);
for (int i = 0; i < N; i++) {
for (int j = 0; j < K; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}
free(threads);
free(thread_nums);
return 0;
}
```
这个代码会读入三个整数N、M和K,分别表示矩阵A、B和C的维度,然后随机生成A和B矩阵的值,最后使用多线程计算C矩阵的值,并输出结果。
代码中使用了pthread库来创建线程,并使用了pthread_create()和pthread_join()函数来创建和等待线程。具体来说,代码中会先创建num_threads个线程,并将线程号存储在thread_nums数组中。然后每个线程会计算C矩阵的一部分,具体的计算范围是根据线程号和矩阵维度计算得到的。最后主线程会等待所有线程计算完毕,并输出C矩阵的值。
阅读全文