समस्या विवरण
यहां हम देखेंगे कि मल्टीथ्रेडेड वातावरण का उपयोग करके मैट्रिक्स जोड़ और घटाव कैसे करें। C या C++ में एक साथ कई थ्रेड्स को निष्पादित करने के लिए pthread का उपयोग किया जाता है।
दो मैट्रिक्स A और B हैं। प्रत्येक मैट्रिक्स का क्रम (m x n) है। प्रत्येक थ्रेड प्रत्येक पंक्ति लेगा, और जोड़ या घटाव करेगा। इसलिए m पंक्तियों के लिए, m अलग-अलग थ्रेड्स हैं।
C++ प्रोग्राम उदाहरण
#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;
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;
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 << "मैट्रिक्स A: " << endl;
for(int i = 0; i < MAX; i++) {
for(int j = 0; j < MAX; j++)
cout << AMat[i][j] << " ";
cout << endl;
}
cout << "\nमैट्रिक्स 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 << "\nजोड़: " << endl;
for(int i = 0; i < MAX; i++) {
for(int j = 0; j < MAX; j++)
cout << add[i][j] << " ";
cout << endl;
}
cout << "\nघटाव: " << 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();
}
आउटपुट
मैट्रिक्स A: 10 20 30 40 50 60 70 80 50 मैट्रिक्स B: 80 60 20 30 20 15 10 14 35 जोड़: 90 80 50 70 70 75 80 94 85 घटाव: -70 -40 10 10 30 45 60 66 15