কম্পিউটার টিউটোরিয়াল

C/C++ প্রোগ্রামে পিথ্রেড ব্যবহার করে ম্যাট্রিক্স আডিশন ও সাবট্র্যাকশন


ভূমিকা

দুটি ম্যাট্রিক্স A এবং B দেওয়া আছে (আকার m×n)। পিথ্রেড (pthread) ব্যবহার করে মাল্টিথ্রেডিং এনভায়রনমেন্টে ম্যাট্রিক্স যোগ ও বিয়োগ করা হয়। প্রতিটি থ্রেড একটি সারি (row) হ্যান্ডেল করে।

C++ প্রোগ্রাম উদাহরণ

#include 
#include 
#include 
#define CORE 3
#define MAX 3
using namespace std;

int A[MAX][MAX] = {{10,20,30},{40,50,60},{70,80,50}};
int B[MAX][MAX] = {{80,60,20},{30,20,15},{10,14,35}};
int add[MAX][MAX], sub[MAX][MAX];
pthread_t threads[CORE*2];

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] = A[i][j] + B[i][j];
    return NULL;
}

void* subtractMatrices(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] = A[i][j] - B[i][j];
    return NULL;
}

int main() {
    int step = 0;
    for (int i = 0; i < CORE; i++) {
        pthread_create(&threads[i], NULL, addMatrices, (void*)step);
        pthread_create(&threads[i+CORE], NULL, subtractMatrices, (void*)step);
        step++;
    }
    for (int i = 0; i < CORE*2; i++) pthread_join(threads[i], NULL);
    
    cout << "Addition:\n";
    for (int i = 0; i < MAX; i++) {
        for (int j = 0; j < MAX; j++) cout << add[i][j] << " ";
        cout << endl;
    }
    cout << "Subtraction:\n";
    for (int i = 0; i < MAX; i++) {
        for (int j = 0; j < MAX; j++) cout << sub[i][j] << " ";
        cout << endl;
    }
    return 0;
}

আউটপুট

Addition:
90 80 50
70 70 75
80 94 85

Subtraction:
-70 -40 10
10 30 45
60 66 15
  1. সি/সি++-এ exit(), abort() ও assert()

  2. সি/সি++-এ strdup() ও strndup()

  3. C++-এ ফাংশন কল বাই অ্যাড্রেস ব্যবহার করে যোগ ও বিয়োগ একসাথে

  4. C++-এ DNF অ্যালগরিদম দিয়ে ০, ১, ২ সর্ট করা