Question: #include #include #include #include / / Mutex to protect the shared accumulator pthread _ mutex _ t mutex; / / Shared accumulator for counting prime
#include
#include
#include
#include
Mutex to protect the shared accumulator
pthreadmutext mutex;
Shared accumulator for counting prime numbers and sum
int primecount ;
int primesum ;
Returns whether num is prime
int isprimeint num
if num
return ;
for int i ; i i num; i
if num i
return ;
return ;
Thread function to count prime numbers
void countprimesvoid rank
long myrank longrank;
int start myrank BOUND threadcount;
int end myrank BOUND threadcount;
if myrank threadcount
end BOUND; Handle the remainder
int localcount ;
for int i start; i end; i
if isprimei
localcount;
Update the global count using a mutex
pthreadmutexlock&mutex;
primecount localcount;
pthreadmutexunlock&mutex;
return NULL;
int mainint argc,char argv
ifargc
printfPlease enter two valid number
;
return ;
give the two vaue to num and num
int childthreads atoiargv;
int maxnumber atoiargv;
Initialize mutex
pthreadmutexinit&mutex, NULL;
Create an array of thread handles
pthreadt threadhandles mallocchildthreads sizeofpthreadt;
Create threads
for long thread ; thread childthreads; thread
pthreadcreate&threadhandlesthread NULL, countprimes, voidthread;
Join threads
for long thread ; thread childthreads; thread
pthreadjointhreadhandlesthread NULL;
Print the final result
printfGRAND SUM IS d COUNT IS d primesum, primecount;
Clean up
freethreadhandles;
pthreadmutexdestroy&mutex;
return ;
check wrong in my code
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
