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
pthread_mutex_t mutex;
// Shared accumulator for counting prime numbers and sum
int prime_count =0;
int prime_sum =0;
// Returns whether num is prime
int isprime(int num){
if (num <2){
return 0;
}
for (int i =2; i * i <= num; ++i){
if (num % i ==0){
return 0;
}
}
return 1;
}
// Thread function to count prime numbers
void* count_primes(void* rank){
long my_rank =(long)rank;
int start = my_rank *(BOUND / thread_count);
int end =(my_rank +1)*(BOUND / thread_count);
if (my_rank == thread_count -1){
end = BOUND; // Handle the remainder
}
int local_count =0;
for (int i = start; i < end; ++i){
if (is_prime(i)==1){
++local_count;
}
}
// Update the global count using a mutex
pthread_mutex_lock(&mutex);
prime_count += local_count;
pthread_mutex_unlock(&mutex);
return NULL;
}
int main(int argc,char *argv[]){
if(argc !=3){
printf("Please enter two valid number
");
return 0;
}
//give the two vaue to num1 and num2
int childthreads = atoi(argv[1]);
int maxnumber = atoi(argv[2]);
// Initialize mutex
pthread_mutex_init(&mutex, NULL);
// Create an array of thread handles
pthread_t* thread_handles = malloc(childthreads* sizeof(pthread_t));
// Create threads
for (long thread =0; thread < childthreads; ++thread){
pthread_create(&thread_handles[thread], NULL, count_primes, (void*)thread);
}
// Join threads
for (long thread =0; thread < childthreads; ++thread){
pthread_join(thread_handles[thread], NULL);
}
// Print the final result
printf("GRAND SUM IS %d, COUNT IS %d", prime_sum, prime_count);
// Clean up
free(thread_handles);
pthread_mutex_destroy(&mutex);
return 0;
}
check wrong in my code

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!