利用多线程在 C/C++ 中进行矩阵加减法运算
本文将说明如何使用多线程环境执行矩阵加法和减法操作。pthread 用于同时执行 C 或 C++ 中的多个线程。
有 A 和 B 两个矩阵。每个矩阵的阶数为 (m x n)。每个线程将取每一行,并执行加法或减法。所以对于 m 行,有 m 个不同的线程。
例子
#include<iostream>
#include <pthread.h>
#include <cstdlib>
#include <cstdint>
#define CORE 3
#define MAX 3
using namespace std;
int AMat[MAX][MAX] = {{10, 20, 30},
{40, 50, 60},
{70, 80, 50}
};
int BMat[MAX][MAX] = {{80, 60, 20},
{30, 20, 15},
{10, 14, 35}
};
pthread_t thread[CORE * 2];
int add[MAX][MAX], sub[MAX][MAX];
void* addMatrices(void* arg) {
intptr_t core = (intptr_t)arg;
// Each thread computes 1/3rd of matrix addition
for (int i = core * MAX / 3; i < (core + 1) * MAX / 3; i++) {
for (int j = 0; j < MAX; j++) {
add[i][j] = AMat[i][j] + BMat[i][j];
}
}
}
void* subtraction(void* arg) {
intptr_t core = (intptr_t)arg;
// Each thread computes 1/3rd of matrix subtraction
for (int i = core * MAX / 3; i < (core + 1) * MAX / 3; i++) {
for (int j = 0; j < MAX; j++) {
sub[i][j] = AMat[i][j] - BMat[i][j];
}
}
}
void display(){
cout << "Matrix A: " << endl;
for(int i = 0; i < MAX; i++) {
for(int j = 0; j < MAX; j++) {
cout << AMat[i][j] << " ";
}
cout << endl;
}
cout << "\nMatrix B: " << endl;
for(int i = 0; i < MAX; i++) {
for(int j = 0; j < MAX; j++) {
cout << BMat[i][j] << " ";
}
cout << endl;
}
}
void displayRes(){
cout << "\nAddition: " << endl;
for(int i = 0; i < MAX; i++) {
for(int j = 0; j < MAX; j++) {
cout << add[i][j] << " ";
}
cout << endl;
}
cout << "\nSubtraction: " << endl;
for(int i = 0; i < MAX; i++) {
for(int j = 0; j < MAX; j++) {
cout << sub[i][j] << " ";
}
cout << endl;
}
}
main() {
display();
int step = 0;
for (int i = 0; i < CORE; i++) {
pthread_create(&thread[i], NULL, &addMatrices, (void*)step);
pthread_create(&thread[i + CORE], NULL, &subtraction, (void*)step);
step++;
}
for (int i = 0; i < CORE * 2; i++) {
pthread_join(thread[i], NULL);
}
displayRes();
}输出
Matrix A: 10 20 30 40 50 60 70 80 50 Matrix B: 80 60 20 30 20 15 10 14 35 Addition: 90 80 50 70 70 75 80 94 85 Subtraction: -70 -40 10 10 30 45 60 66 15
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
JavaScript
PHP