Question

//In this assignment, we use multiple threads to calculate the sum // 1*1 + 2*2 +...

//In this assignment, we use multiple threads to calculate the sum
// 1*1 + 2*2 + 3*3 + 4*4 + ... + n*n
// Note we should know from CSE2500 that this sum is
// n*(n+1)*(2*n+1)/6
// We a n value, we will create 2*n threads to do the calculation so that
// we can have a race condition.
// Before you change the code, read the code and run the code and see what
// happens. Do we already get the result sum?
// Read the code carefully and make changes to the code.
// Use mutex to ensure we always get the right sum.

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <pthread.h>
#include <unistd.h>
#define MAX 1000


int n;
unsigned long sum = 0;
pthread_mutex_t mutex;

void* calculate(void* threadarg)
{

//fill in one line of code blew

if(n > 0)
{
sum += n*n;
//do not delete the following line of code
//this line helps us to see wrong results
sleep(0);
n--;
}
//fill in one line of code below
  
pthread_exit(NULL);
}

int main(int argc, char *argv[])
{

if(argc!=2)
{
printf("Usage: %s n (1 - 500)\n", argv[0]);
return -1;
}

n = atoi(argv[1]);
assert(n >= 1 && n <= MAX/2);

//save n to k for later use
int k = n;
int m = 2*n;

//fill in one line of code below

pthread_t threads[MAX];
int rc, t;
for( t=0; t<m; t++ ) {
//Since we do not need to pass any arguments to the thread, we pass a NULL
rc = pthread_create(&threads[t], NULL, calculate, NULL);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}

for( t=0; t<m; t++ )
{
rc = pthread_join( threads[t], NULL );
if( rc ){
printf("ERROR; return code from pthread_join() is %d\n", rc);
exit(-1);
}
}
//fill in one line of code below

unsigned long correct_sum = k*(k+1)*(2*k+1)/6;
printf("thread sum : %ld correct sum : %ld\n", sum, correct_sum);
return 0;
}

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

//In this assignment, we use multiple threads to calculate the sum
// 1*1 + 2*2 + 3*3 + 4*4 + ... + n*n
// Note we should know from CSE2500 that this sum is
// n*(n+1)*(2*n+1)/6
// We a n value, we will create 2*n threads to do the calculation so that
// we can have a race condition.
// Before you change the code, read the code and run the code and see what
// happens. Do we already get the result sum?
// Read the code carefully and make changes to the code.
// Use mutex to ensure we always get the right sum.

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <pthread.h>
#include <unistd.h>
#define MAX 1000


int n;
unsigned long sum = 0;
pthread_mutex_t mutex;

void* calculate(void* threadarg)
{

//fill in one line of code blew
pthread_mutex_lock(&mutex);
if(n > 0)
{
sum += n*n;
//do not delete the following line of code
//this line helps us to see wrong results
sleep(0);
n--;
}
//fill in one line of code below
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}

int main(int argc, char *argv[])
{

if(argc!=2)
{
printf("Usage: %s n (1 - 500)\n", argv[0]);
return -1;
}

n = atoi(argv[1]);
assert(n >= 1 && n <= MAX/2);

//save n to k for later use
int k = n;
int m = 2*n;

//fill in one line of code below
if (pthread_mutex_init(&mutex, NULL) != 0)
{
printf("\n mutex init has failed\n");
return 1;
}

pthread_t threads[MAX];
int rc, t;
for( t=0; t<m; t++ ) {
//Since we do not need to pass any arguments to the thread, we pass a NULL
rc = pthread_create(&threads[t], NULL, calculate, NULL);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}

for( t=0; t<m; t++ )
{
rc = pthread_join( threads[t], NULL );
if( rc ){
printf("ERROR; return code from pthread_join() is %d\n", rc);
exit(-1);
}
}
//fill in one line of code below
pthread_mutex_destroy(&mutex);
unsigned long correct_sum = k*(k+1)*(2*k+1)/6;
printf("thread sum : %ld correct sum : %ld\n", sum, correct_sum);
return 0;
}

Add a comment
Know the answer?
Add Answer to:
//In this assignment, we use multiple threads to calculate the sum // 1*1 + 2*2 +...
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
  • //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...

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

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

  • Pleas help I need to create and array to add to my code something like this...

    Pleas help I need to create and array to add to my code something like this for (i = 0; i < NUM_THREADS; ++i) { thr_data[i].tid = i; if ((rc = pthread_create(&thr[i], NULL, thr_func, &thr_data[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\n", rc); return EXIT_FAILURE; ::::::::: CODE ::::::::::::: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h>    int sharedVar = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; /* thread handler */ void *threadHandler(void *vargp) {    int i = 0;    pthread_mutex_lock(&mutex);   ...

  • i want to fix the solution and provide an explanation why the pthread_join is not working...

    i want to fix the solution and provide an explanation why the pthread_join is not working as intended? #include <stdio.h> /* standard I/O routines */ #include <pthread.h> /* pthread functions and data structures */ void* PrintHello(void* data) { pthread_t tid = (pthread_t)data; /* data received by thread */ pthread_join(tid, NULL); /* wait for thread tid */ printf("Hello from new thread %u - got %u\n", pthread_self(), data); pthread_exit(NULL); /* terminate the thread */ } /* like any C program, program's execution...

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

  • 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. (50 pts) Write a C or C++ program A6p1.c(pp) that accepts one command line argument which is an integer...

    1. (50 pts) Write a C or C++ program A6p1.c(pp) that accepts one command line argument which is an integer n between 2 and 6 inclusive. Generate a string of 60 random upper case English characters and store them somewhere (e.g. in a char array). Use pthread to create n threads to convert the string into a complementary string ('A'<>'Z', 'B'<->'Y', 'C''X', etc). You should divide this conversion task among the n threads as evenly as possible, Print out the...

  • Combine two codes (code 1) to get names with(code 2) to get info: Code 1: #include<unistd.h>...

    Combine two codes (code 1) to get names with(code 2) to get info: Code 1: #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<dirent.h> #include<stdio.h> #include<stdlib.h> void do_ls(char []); int main(int argc,char *argv[]) { if(argc == 1) do_ls("."); else while(--argc){ printf("%s:\n",*++argv); do_ls(*argv); } } void do_ls(char dirname[]) { DIR *dir_ptr; struct dirent *direntp; if((dir_ptr = opendir(dirname)) == NULL) fprintf(stderr,"ls1:cannot open %s\n",dirname); else { while((direntp = readdir(dir_ptr)) != NULL) printf("%s\n",direntp->d_name); closedir(dir_ptr); } } ____________________________ code 2: #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> void show_stat_info(char *,...

  • P5: The program below has a parent thread that is a writer and 2 child threads that are both read...

    I need help with the following question: P5: The program below has a parent thread that is a writer and 2 child threads that are both readers. Complete the "child" function so that readers can continuously print the value of x" whenever the writer is not writing. No reader should starve while the other reader is reading sem t mutex, Xw mutex; int x; int read count = 0; int main (int argc, char "argv[]) { sem init (&mutex, 0,...

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