Thread

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

#include <pthread.

h>
#include <stdio.h>

#define NUM_THREADS 3
#define MAX_SIZE 10

int size;
int matrix1[MAX_SIZE][MAX_SIZE];
int matrix2[MAX_SIZE][MAX_SIZE];
int result[NUM_THREADS][MAX_SIZE][MAX_SIZE];

void *addition(void *param);


void *subtraction(void *param);
void *multiplication(void *param);

int main()
{
int i, j;
pthread_t tid[NUM_THREADS];
pthread_attr_t attr;
int scope;

// get the default attributes


pthread_attr_init(&attr);

// get the current scope


if (pthread_attr_getscope(&attr, &scope) != 0)
{
fprintf(stderr, "Unable to get scheduling scope\n");
return 1;
}

if (scope == PTHREAD_SCOPE_PROCESS)
printf("PTHREAD SCOPE PROCESS\n");
else if (scope == PTHREAD_SCOPE_SYSTEM)
printf("PTHREAD SCOPE SYSTEM\n");
else
{
fprintf(stderr, "Illegal scope value.\n");
return 1;
}

// set the scheduling algorithm to PTHREAD_SCOPE_SYSTEM


pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);

// Get the size of the matrix from the user


printf("Enter the size of the square matrix (up to %d): ", MAX_SIZE);
scanf("%d", &size);

if (size <= 0 || size > MAX_SIZE)


{
fprintf(stderr, "Invalid matrix size\n");
return 1;
}

// Get values for matrix1 from the user


printf("Enter values for matrix1:\n");
for (i = 0; i < size; i++)
for (j = 0; j < size; j++)
scanf("%d", &matrix1[i][j]);

// Get values for matrix2 from the user


printf("Enter values for matrix2:\n");
for (i = 0; i < size; i++)
for (j = 0; j < size; j++)
scanf("%d", &matrix2[i][j]);

// Create the threads for addition, subtraction, and multiplication


pthread_create(&tid[0], &attr, addition, NULL);
pthread_create(&tid[1], &attr, subtraction, NULL);
pthread_create(&tid[2], &attr, multiplication, NULL);

// Join the threads


for (i = 0; i < NUM_THREADS; i++)
pthread_join(tid[i], NULL);

// Print the result matrices


printf("\nResult of addition:\n");
for (i = 0; i < size; i++)
{
for (j = 0; j < size; j++)
printf("%d\t", result[0][i][j]);
printf("\n");
}

// ... Similar print statements for subtraction and multiplication ...

return 0;
}

// Each thread will perform matrix addition


void *addition(void *param)
{
int i, j;

for (i = 0; i < size; i++)


for (j = 0; j < size; j++)
result[0][i][j] = matrix1[i][j] + matrix2[i][j];

pthread_exit(0);
}

// Each thread will perform matrix subtraction


void *subtraction(void *param)
{
int i, j;

for (i = 0; i < size; i++)


for (j = 0; j < size; j++)
result[1][i][j] = matrix1[i][j] - matrix2[i][j];

pthread_exit(0);
}

// Each thread will perform matrix multiplication


void *multiplication(void *param)
{
int i, j, k;
for (i = 0; i < size; i++)
for (j = 0; j < size; j++)
{
result[2][i][j] = 0;
for (k = 0; k < size; k++)
result[2][i][j] += matrix1[i][k] * matrix2[k][j];
}

pthread_exit(0);
}

You might also like