>  기사  >  백엔드 개발  >  pthread를 사용하여 C/C++에서 행렬 덧셈 및 뺄셈 구현

pthread를 사용하여 C/C++에서 행렬 덧셈 및 뺄셈 구현

WBOY
WBOY앞으로
2023-08-28 09:05:071170검색

pthread를 사용하여 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

위 내용은 pthread를 사용하여 C/C++에서 행렬 덧셈 및 뺄셈 구현의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제