Write a C or C program A6p2.c(pp) that accepts one command line argument which is an integer n between 2 and 4 inclusive. Generate 60 random integers between 1 and 49 inclusive and store them in a 5 by 12 two dimensional integer array (i.e.,int a[5][12];). Use pthread to create n threads to square all 60 array elements in place. You should divide this update task among the n threads as evenly as possible. Print the array both before and after the update separately as 5 by 12 matrices.

Respuesta :

Answer:

The code is as given below. The output is attached as the attachments

Explanation:

#include <iostream>

#include <cstdlib>

#include <pthread.h>

using namespace std;

#define c 12 // defining number of columns

#define r 5 //defining number of rows

int chunk; //initializing variable chunk

int n=0; //defining variable n as 0

int arry[r][c] ; //initializing the array as 5x12

void Squared(void threadid) {

long td; //initializing the variable td

 

td = (long)threadid; //typecasting threader to long

 

int s = td * chunk; //defining variable s for the start

int e=s+chunk-1;//defining variable e for the end

for(int i=0; i<r; i++){ //initializing for loop for rows

for(int j=0;j<c;j++){ //initializing for loop for columns

int pos = i*c + j; //defining variable

if(pos>=s&&pos<=e)//condition to make sure the values in within the chunk range

{

arry[i][j]=arry[i][j]*arry[i][j]; //squaring the terms

}

}

}

pthread_exit(NULL);

}

int main () {

cin>>n; //taking number n from 2 to 4 inclusive from the user

pthread_t threads[n];

int rc; //initializing variable rc for threads

int i,j,k; //initializing variables i,j,k

//filling array with data

for(i=0;i<r;i++) //for loop for rows

{

for(j=0;j<c;j++)  //for loop for columns

{

arry[i][j]=(rand() % 49) + 1;  //Creating random integers

}

}

//Printing Random Array

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

{

cout<<"\n";

for(j=0;j<c;j++)

{

cout<<arry[i][j]<<"\t";

}

}

chunk = (60 + n - 1) / n; // divide by threads rounded up.

for( i = 0; i < n; i++ ) {

cout << "\n main() : creating thread, " << i << endl;

rc = pthread_create(&threads[i], NULL, Squared, (void *)i); //creating the threads

if (rc) {

cout << "Error:unable to create thread," << rc << endl;

exit(-1);

}

}

//Printing Result Array

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

{

cout<<"\n";

for(j=0;j<c;j++)

{

cout<<arry[i][j]<<"\t";

}

}

pthread_exit(NULL);

}

Ver imagen danialamin
Ver imagen danialamin
Ver imagen danialamin