In: Other
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 (e.g.,int a[5][12];). Use pthread to create n threads to square all 60 array elements. 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.
Note: Must use pthread to divide the update task among the threads.
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define COLS 12
#define ROWS 5
int chunkSize;
int n=0;
int arr[ROWS][COLS] ;
void DoSquare(void threadid) {
long tid;
tid = (long)threadid;
int start = tid * chunkSize;
int end=start+chunkSize-1;
for(int i=0; i<ROWS; i++){
for(int j=0;j<COLS;j++){
int position = i*COLS + j;
if(position>=start&&position<=end)
{
arr[i][j]=arr[i][j]*arr[i][j];
}
}
}
pthread_exit(NULL);
}
int main () {
cin>>n;
pthread_t threads[n];
int rc;
int i,j,k;
//fill array wil data
for(i=0;i<ROWS;i++)
{
for(j=0;j<COLS;j++)
{
arr[i][j]=(rand() % 49) + 1;
}
}
//Printing Random Array
for(i=0;i<ROWS;i++)
{
cout<<"\n";
for(j=0;j<COLS;j++)
{
cout<<arr[i][j]<<"\t";
}
}
chunkSize = (60 + n - 1) / n; // divide by threads rounded up.
for( i = 0; i < n; i++ ) {
cout << "\nmain() : creating thread, " << i <<
endl;
rc = pthread_create(&threads[i], NULL, DoSquare, (void
*)i);
if (rc) {
cout << "Error:unable to create thread," << rc <<
endl;
exit(-1);
}
}
//Printing Resulter Array
for(i=0;i<ROWS;i++)
{
cout<<"\n";
for(j=0;j<COLS;j++)
{
cout<<arr[i][j]<<"\t";
}
}
pthread_exit(NULL);
}