Pthreads矩阵-向量程序
时间: 2023-12-31 17:07:10 浏览: 36
以下是使用Pthreads编写的矩阵-向量乘法程序的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MATRIX_SIZE 1000
#define THREADS_NUM 4
int matrix[MATRIX_SIZE][MATRIX_SIZE];
int vector[MATRIX_SIZE];
int result[MATRIX_SIZE];
int chunk_size;
void* multiply(void* arg) {
int start = *(int*)arg * chunk_size;
int end = start + chunk_size;
for (int i = start; i < end; i++) {
int sum = 0;
for (int j = 0; j < MATRIX_SIZE; j++) {
sum += matrix[i][j] * vector[j];
}
result[i] = sum;
}
return NULL;
}
int main() {
// Initialize matrix and vector
for (int i = 0; i < MATRIX_SIZE; i++) {
for (int j = 0; j < MATRIX_SIZE; j++) {
matrix[i][j] = rand() % 100;
}
vector[i] = rand() % 100;
}
// Divide work among threads
chunk_size = MATRIX_SIZE / THREADS_NUM;
pthread_t threads[THREADS_NUM];
int thread_args[THREADS_NUM];
for (int i = 0; i < THREADS_NUM; i++) {
thread_args[i] = i;
pthread_create(&threads[i], NULL, multiply, &thread_args[i]);
}
// Wait for threads to finish
for (int i = 0; i < THREADS_NUM; i++) {
pthread_join(threads[i], NULL);
}
// Verify result
int expected_result[MATRIX_SIZE];
for (int i = 0; i < MATRIX_SIZE; i++) {
expected_result[i] = 0;
for (int j = 0; j < MATRIX_SIZE; j++) {
expected_result[i] += matrix[i][j] * vector[j];
}
}
for (int i = 0; i < MATRIX_SIZE; i++) {
if (result[i] != expected_result[i]) {
printf("Error: result[%d] = %d, expected_result[%d] = %d\n",
i, result[i], i, expected_result[i]);
return 1;
}
}
printf("Success!\n");
return 0;
}
```
该程序将矩阵和向量初始化为随机值,然后将工作分配给多个线程。每个线程计算矩阵的一部分乘以向量的结果,并将结果存储在结果数组中。最后,程序验证结果是否正确,并打印成功或失败消息。
请注意,该程序可能会因为线程数量与矩阵大小不匹配而导致结果不正确。在实际应用中,您可能需要根据系统配置动态选择线程数量。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)