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 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.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

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.

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.

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;
}

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;
}
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...

  • Using C programming please 5. Write a multithreaded program to do the following: Accepts two positive...

    Using C programming please 5. Write a multithreaded program to do the following: Accepts two positive integers from the command line as the amounts to withdraw a. and deposit from an account. b. Creates two threads to perform withdraw and deposit operations repectively. Passes the amount to withdraw/deposit as the parameter to thread's runner function c. Waits for both threads to terminate. Since both threads need to update the account balance, it is necessary to protect sections. You may use...

  • operating system engineering , please read the question and solve on the given skeleton code ....

    operating system engineering , please read the question and solve on the given skeleton code . Write a multi-threaded program with Semaphores as counters and pthread_mutex_t mutex to solve the producer-consumer problem: A bounded buffer is simply a global integer array of size N (2) which can be accessed by multiple threads. • Create two types of threads - Producer (2) and Consumer (2). Producers will write to the buffer, and the consumers will read the buffer. In this scenario,...

  • 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,...

  • 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; //...

  • any help! my program not working , there is an error but cannot solve it i...

    any help! my program not working , there is an error but cannot solve it i did this program after editing a previous program  and i tried to follow the following ; 1. Instead of printing the prime numbers from 2 to n, your program will print the first n prime numbers. 2. It will be an error if n is less than 1. Exampl: $ ./a 1 2 3 #include<stdio.h> 4 int p; // p is the global variable. 5...

  • You are given a sample code that when edited/ improved/completed -will work as a producer consumer...

    You are given a sample code that when edited/ improved/completed -will work as a producer consumer synchronized solution. In addition to the counter, you will implement a circular linked list as a buffer of size 200 that stores data items 0 or 1. The producer and consumer take *random* turns to produce and consume- *random* numbers of elements ( turning 1 to a 0 and visa-versa-each time, as discussed in class). After each turn of the producer and/or consumer, your...

  • In c programming The Consumer Submits processing requests to the producer by supplying a file name, its location and a character. It also outputs the contents of the file provided by the producer...

    In c programming The Consumer Submits processing requests to the producer by supplying a file name, its location and a character. It also outputs the contents of the file provided by the producer to the standard output. The Producer Accepts multiple consumer requests and processes each request by creating the following four threads. The reader thread will read an input file, one line at a time. It will pass each line of input to the character thread through a queue...

  • 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...

  • 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...

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