pl do not copy the solution already in chegg. It is wrong and it did not use threads which is the main important concept of this program/. Pl write program with threads.
u can use follwing sample program
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#define NTHREADS 20
void *go(void *);
pthread_t threads[NTHREADS];
int main() {
static int i;
for (i = 0; i < NTHREADS; i++)
pthread_create(&threads[i], NULL, go, &i);
for (i = 0; i < NTHREADS; i++) {
pthread_join(threads[i],NULL);
printf("Thread %d returned
", i);
}
printf("Main thread done.
");
}
void *go(void *arg) {
printf("Hello from thread %d with thread ID %d
", *(int *)arg, (int)pthread_self());
return (NULL);
}
Now solve below"
1. Write a program that uses threads to copy, and update, a matrix in parallel. The goal is to copy the contents of one matrix to another, and to update the original matrix (by multiplying each element by 2).
You may fill in the entries of A and B matrices (double matrixA[N][M], matrixB[M][L] ) using a predefined sequence as below:
x = 0;
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
matrixA[i][j] = x++;
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
matrixB[i][j] = 0;
This creates two matrices, A and B, with A containing a simple sequence of numbers, and B initialized to zeros.
The following are important notes:
The values of N and M must be large to exploit parallelism (e.g. N, M = 1024).
Implement separate functions to print out a matrix, to copy matrixA to matrixB, and to double the values of each element in matrix A.
Do the following:
print matrixA.
launch two separate threads to:
copy matrixA to matrixB
double the values in matrixA
wait for the two threads to complete
print matrixA again.
The main thread needs to wait for the two subroutine threads to complete, but in your first implementation there should be no synchronization between the threads (i.e., do nothing to coordinate their behavior relative to each other).
Repeat the above, but ensure that the copying of the matrix does not start until the doubling is complete (hint: you may use a spin-lock/loop if you wish, but clearly explain how you are ensuring that the two independent threads wait appropriately).