Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C or C++ program A6p4.c (or A6p4.cpp ) that accepts one command line arg

ID: 3825152 • Letter: W

Question

Write a C or C++ program A6p4.c (or A6p4.cpp) that accepts one command line argument which is an integer n between 2 and 4 inclusive. Generate 60 random integers in the range of [1,99] and store them in a 5 by 12 two dimensional integer array (say, a[5][12]). Use pthread to create n threads to update these numbers according the following rule: if a number is even increment it by one; if a number is odd decrement it by one. You should divide this update task among the n threads as evenly as possible. Print the array before the update and after the update separately as 5 by 12 two dimensional arrays.

Explanation / Answer

#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <pthread.h>

using namespace std;
static int a[5][12];
void *alterArray(void *argument){
for(int i=0;i<5;i++)
{
for(int j=0;j<12;j++)
{
if(a[i][j]%2==0)
       {
           a[i][j]=a[i][j]+1;
       }
       else
       {
           a[i][j]=a[i][j]-1;
       }

}

}
}

int main()
{
int n;

cout << "Enter no between 2 and 4" << endl;
cin>> n;
for(int i=0;i<5;i++)
{
for(int j=0;j<12;j++)
{
a[i][j]=rand() % 100;
cout <<a[i][j]<<" ";
}
cout<<" ";
}

pthread_t thread1, thread2, thread3, thread4;
int i1,i2,i3,i4;
   switch(n)
   {
       case 2: i1 = pthread_create( &thread1, NULL, alterArray, (void*) "thread 1");
               i2 = pthread_create( &thread2, NULL, alterArray, (void*) "thread 2");
               pthread_join(thread1,NULL);
               pthread_join(thread2,NULL);
               break;
       case 3: i1 = pthread_create( &thread1, NULL, alterArray, (void*) "thread 1");
               i2 = pthread_create( &thread2, NULL, alterArray, (void*) "thread 2");
               i3 = pthread_create( &thread3, NULL, alterArray, (void*) "thread 3");
               pthread_join(thread1,NULL);
           pthread_join(thread2,NULL);
               pthread_join(thread3,NULL);
               break;
       case 4: i1 = pthread_create( &thread1, NULL, alterArray, (void*) "thread 1");
               i2 = pthread_create( &thread2, NULL, alterArray, (void*) "thread 2");
               i3 = pthread_create( &thread3, NULL, alterArray, (void*) "thread 3");
               i4 = pthread_create( &thread4, NULL, alterArray, (void*) "thread 4");
               pthread_join(thread1,NULL);
           pthread_join(thread2,NULL);
               pthread_join(thread3,NULL);
               pthread_join(thread4,NULL);
               break;
   }


for(int i=0;i<5;i++)
{
for(int j=0;j<12;j++)
{
cout<<a[i][j]<<" ";
}
cout<<" ";
}
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote