Question

Help with a Parallel and Distributed Programming assignment. In this assignment, you will be expl...

Help with a Parallel and Distributed Programming assignment.

In this assignment, you will be exploring different methods of counting the prime numbers between 1 and N. You will use 8 threads, and each will be given a range in which to count primes. The question is: where do you store your counter? Do you use a local variable? Do you use a global variable?

Please use the following function to determine whether an integer number is a prime.

// Return 1 if n is prime, else 0

int is_prime(int n) {

  if (n < 2)return 0;

  if (n == 2)return 1;

  if (n % 2 == 0)return 0;

  for (int i=3; i < n; i += 2) {

    if (n % i == 0) return 0;

  }

  return 1;

}

Part 1: Simple Solutions

Each thread counts a section of the array (the first thread gets numbers 1 through N/8, the second threads gets numbers N/8+1 through 2*N/8, etc.) - it is alright to mandate that N be a multiple of 8 so that it divides evenly among the threads. It doesn't matter if N is a global variable, constant, or command line input. I have found that the value N=800000 is a good one for my desktop (it takes long enough for me to time it, but not too long).

Solution 1: Global Counter (Scalar)

Use a global variable to keep track of the total count of prime numbers. Since all threads will be reading and writing to it like crazy, we need to protect it with a mutexlock. So, make a global variable mutexlock. Every time a thread sees a prime number, it locks the lock, updates the counter, and then unlocks the lock.

Solution 2: Global Counter (Array), Global Scalar Update

Use a global variable that is an array of counters - one counter for each thread. When a thread sees a prime number, it updates its entry in the global array. Before the thread exits, it should update a mutexprotected global scalar variable.

Solution 3: Global Counter (Array), Global Array Update – No mutex required

Use a global variable that is an array of counters - one counter for each thread. When a thread sees a prime number, it updates its entry in the global array. The main code should be responsible for summing the entries in this array. I do this after each thread is joined.

Solution 4: Local Counter, Global Scalar Update

Use a local variable to keep track of an individual thread's prime number count. Then, before the thread exits, it should update a mutex protected global scalar value.

This is what I have so far.

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h> //for the time
#include <pthread.h> //include pthreads

// Return 1 if n is prime, else 0
int is_prime(int n) {
    if (n < 2) return 0;
    if (n == 2) return 1;
    if (n % 2 == 0) return 0;
    for (int i=3; i < n; i += 2) {
        if (n % i == 0) return 0;
    }
    return 1;
}

int main(int argc, char* argv[]){
    pthread_t tid[8]; //We're only using 8 threads
    pthread_attr_t attr; //Thread attribute object identifier

    //In addition to checking the primality of all these numbers,
    //we have to log the time it took for the program to complete its operations
    struct timeval start, end; //timeval structs contain tv_sec & tv_usec (microseconds)
    gettimeofday(&start, NULL); //2nd argument is timezone

    long input = strtol(argv[1], (char**) NULL, 10); //Convert the user input to a long type

    //The pthreads code should should somewhere between here and the
    //next gettimeofday() call


    pthread_attr_init(&attr); //Create thread attribute object

    //This SHOULD create 8 threads and send an 8th of the data to each
    //is_prime() function call
    for (int i=0; i<8; i+=1){
        printf("Half of data: %i\n", i);
        for (long j=i*input/8+1; j<=(i+1)*input/8; j+=1){
            pthread_create(&tid[i], &attr, is_prime, j);
            int result = is_prime(j);
            /*if (result){
                printf("%li is prime\n", j);
            }else{
                printf("%li is not prime\n", j);
            }*/
        }
    }
    for (int i=0; i<8; i+=1){
        //pthread_join(tid[i], NULL);
        //Suspend execution of tid[i] until tid[i-1] terminates
    }

    //We need to check the primality of each individual number
    //between 1 and N (the user's input)
    /*for (long i = 1; i <= input; i+=1){
        is_prime(i); //Calls is_prime with i as its argument
    }*/


    //Log the time the operation ended so we can show how long it took
    gettimeofday(&end, NULL);

    //Print how long the operations took
    printf("Time used for operations: %ld\n", 
            ((end.tv_sec * 1000000 + end.tv_usec) - 
                (start.tv_sec * 1000000 + start.tv_usec))
          );
    
    return 0;
}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:

We will store the value of Counter as a global variable to betterly access the variable.

Benefit of declaring the counter variable as Global:

1. Global variable is accessible through out the program so from anywhere in the program we can access the value of global (Counter) variable.

2. Global variable initializes its value at the time of object creation through constructor.

3. We can access the value of global variable in inside of any method or in any class.

Add a comment
Know the answer?
Add Answer to:
Help with a Parallel and Distributed Programming assignment. In this assignment, you will be expl...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Help with a Parallel and Distributed Programming assignment. In this assignment, you will be expl...

    Help with a Parallel and Distributed Programming assignment. In this assignment, you will be exploring different methods of counting the prime numbers between 1 and N. You will use 8 threads, and each will be given a range in which to count primes. The question is: where do you store your counter? Do you use a local variable? Do you use a global variable? Please use the following function to determine whether an integer number is a prime. // Return...

  • In C using the following 2 files to create a 3rd file that uses multiple threads...

    In C using the following 2 files to create a 3rd file that uses multiple threads to improve performance. Split the array into pieces and each piece is handled by a different thread. Use 8 threads. run and compile in linux. #include <stdio.h> #include <sys/time.h> #define BUFFER_SIZE 4000000 int countPrime=0; int numbers[BUFFER_SIZE]; int isPrime(int n) { int i; for(i=2;i<n;i++) if (n%i==0) return 0; return 1; } int main() { int i; // fill the buffer for(i=0;i<BUFFER_SIZE;i++) numbers[i] = (i+100)%100000; //...

  • so in this code, it computes the sum 1+2+....+n but i want it to compute 2*(1+2+....+n)...

    so in this code, it computes the sum 1+2+....+n but i want it to compute 2*(1+2+....+n) using semaphores implement solution to the critical section problem #include #include int sum; /* this data is shared by the thread(s) */ void *runner(void *param); /* threads call this function */ int main(int argc, char *argv[]) { pthread_t tid; /* the thread identifier */ pthread_attr_t attr; /* set of thread attributes */ if (argc != 2) { fprintf(stderr,"usage: a.out \n"); return -1; } if...

  • Debugging and testing multithreaded programs is made more difficult compared to dealing with single-threaded programs by...

    Debugging and testing multithreaded programs is made more difficult compared to dealing with single-threaded programs by: 1. the necessity to divide activities into separate and concurrent tasks 2. the existence of many more different execution paths made possible by parallel thread execution 3. multithreading library APIs with confusing semantics -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Consider the following code that creates N threads using the POSIX threading library. The thread function threadFun receives as parameter a thread index (from 0 to N-1). #define NTHREADS 4...

  • I need Help PLZ. I can't solving this in C program Given is a C program count_primes.c, which is an array Generates 10000 six-digit random numbers and then determines the number of primes in that...

    I need Help PLZ. I can't solving this in C program Given is a C program count_primes.c, which is an array Generates 10000 six-digit random numbers and then determines the number of primes in that array. It also measures the time that elapses during the calculation and returns it to the console along with the number of primes it finds. (a) Rewrite the program so that N threads are used to count the primes in the array. Each thread is...

  • How do I do this C++ in a Unix Environment assignment Given dot1m.c 1. The program (dot1m.c) uses...

    How do I do this C++ in a Unix Environment assignment Given dot1m.c 1. The program (dot1m.c) uses mutex to lock and unlock the shared resource (dotstr.sum) for access control as shown below. pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; printf("Thread %ld did %d to %d: mysum=%f global sum=%f\n", offset,start,end,mysum,dotstr.sum); pthread_mutex_unlock (&mutexsum); 2. Modify dot1m.c program to use reader-writer lock (instead of mutex).      Replace the codes (for mutex) by the codes (for reader-writer lock).            To initialize reader-writer lock, pthread_rwlock_initializer.            At the end,...

  • C Programming - RSA Encryption I've tried to write a program that can encrypt and decrypt...

    C Programming - RSA Encryption I've tried to write a program that can encrypt and decrypt strings using RSA and want to be able to integrate it into a header file which contains codes for compression, linked list etc.. However, the use of global variables and fixed size of encryption is making it hard to do so Can someone please help me modify the following the code? I want to be able to just pass it in a string to...

  • C Programming - RSA Encryption I've tried to write a program that can encrypt and decrypt strings using RSA and want...

    C Programming - RSA Encryption I've tried to write a program that can encrypt and decrypt strings using RSA and want to be able to integrate it into a header file which contains codes for compression, linked list etc.. However, the use of global variables and fixed size of encryption is making it hard to do so Can someone please help me modify the following the code? I want to be able to just pass it in a string to...

  • //In this assignment, we use multiple threads to calculate the frequencies of the first digits //of...

    //In this assignment, we use multiple threads to calculate the frequencies of the first digits //of the numbers in an array of long integers #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <assert.h> //#define NUM_THREADS 2 #define DIGITS 10 #define MAX 100000000 unsigned long a[MAX]; struct thread_data { int thread_num; int i, j;                           //the staring and ending index unsigned long freq[DIGITS];           // results }; //initialize the array void init_array(unsigned...

  • I must execute in C using parallel Programming techniques the following serial program: void producer_consumer(int *buffer,...

    I must execute in C using parallel Programming techniques the following serial program: void producer_consumer(int *buffer, int size, int *vec, int n) {    int i, j;    long long unsigned int sum = 0;    for(i=0;i<n;i++) {        if(i % 2 == 0) {   // PRODUCER            for(j=0;j<size;j++) {                buffer[j] = vec[i] + j*vec[i+1];            }        }        else {   // CONSUMER            for(j=0;j<size;j++) {...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT