Modify this code to get a prime number in C language given this requirement 1. Allow 5 threads to concurrently search th

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899603
Joined: Mon Aug 02, 2021 8:13 am

Modify this code to get a prime number in C language given this requirement 1. Allow 5 threads to concurrently search th

Post by answerhappygod »

Modify this code to get a prime number in C language given this
requirement
1. Allow 5 threads to concurrently search the prime numbers
between 1 - 50,000
2. Each thread only needs to analyze​ 10,000 numbers
3. Print the all prime numbers on the display with the main
thread
#include <pthread.h>
#include <stdio.h>
// Compute successive prime numbers (very inef ciently).
// Return the Nth prime number, where N is the value pointed to by
*ARG.
void *compute_prime(void *arg)
{
int candidate = 2;
int n = *((int *)arg);
while (1)
{
int factor, is_prime = 1;
/* Test primality by successive division. */
for (factor = 2; factor < candidate;
++factor)
if (candidate % factor == 0)
{
is_prime = 0;
break;
}
/* Is this the prime number we’re looking for?
*/
if (is_prime)
{
if (--n == 0)
/* Return the desired prime number as
the thread return value. */
return (void *)candidate;
}
++candidate;
}
return NULL;
}
int main()
{
pthread_t thread;
int which_prime = 5133, prime,n;
n = which_prime;
/* Start the computing thread, up to the 5,133th prime
number. */
pthread_create(&thread, NULL, &compute_prime,
&which_prime);
/* Do some other work here... */
/* Wait for the prime number thread to complete, and get the
result. */
pthread_join(thread, (void *)&prime);
/*Print the 5,133th prime it computed. */
printf("The % dth prime number is % d.\n", n, prime);
return 0;
}
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply