Question

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 (atoi(argv[1]) < 0) {
fprintf(stderr,"%d must be >= 0\n",atoi(argv[1]));
return -1;
}
/* get the default attributes */
pthread_attr_init(&attr);
/* create the thread */
pthread_create(&tid,&attr,runner,argv[1]);
/* wait for the thread to exit */
pthread_join(tid,NULL);
printf("sum = %d\n",sum);
}
/* The thread will begin control in this function */
void *runner(void *param)
{
int i, upper = atoi(param);
sum = 0;
for (i = 1; i <= upper; i++)
sum += i;
pthread_exit(0);
}

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

Please find the program using semaphore to protect the critical section when calculating sum in two threads.

Program:

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

/*initialize here itself */
int sum =0; /* this data is shared by the thread(s) */

sem_t mutex;

void *runner(void *param); /* threads call this function */
void *runner_1(void *param); /* threads call this function */

int main(int argc, char *argv[])
{
   pthread_t tid; /* the thread identifier */
   pthread_t tid_1; /* the thread identifier */
   pthread_attr_t attr; /* set of thread attributes */

   /* semaphore initilized to protect multiple threads of process */
   sem_init(&mutex, 0, 1);

if (argc != 2) {
      fprintf(stderr,"usage: thread_sync.exe <integer> \n");
      return -1;
   }
   if (atoi(argv[1]) < 0) {
      fprintf(stderr,"%d must be >= 0\n",atoi(argv[1]));
      return -1;
   }
   /* get the default attributes */
   pthread_attr_init(&attr);

   /* create the thread */
   pthread_create(&tid,&attr,runner,argv[1]);
   pthread_create(&tid_1,&attr,runner_1,argv[1]);

   /* wait for the thread to exit */
   pthread_join(tid,NULL);
   pthread_join(tid_1,NULL);

   sem_destroy(&mutex);
   printf("sum = %d\n",sum);

}

/* The thread will begin control in this function */
void *runner(void *param)
{
   int i, upper = atoi(param);

   /* Wait/Lock using a mutex */
   sem_wait(&mutex);

   for (i = 1; i <= upper; i++)
      sum += i;

   printf("Sum computed in 1st thread is %d\n", sum);

   /* signal/Unlock the mutex */
   sem_post(&mutex);

   pthread_exit(0);
}


/* The thread will begin control in this function */
void *runner_1(void *param)
{
   int i, upper = atoi(param);

   /* Wait/Lock using a mutex */
   sem_wait(&mutex);

   for (i = 1; i <= upper; i++)
      sum += i;

   printf("Sum computed in 2nd thread is %d\n", sum);

   /* signal/Unlock the mutex */
   sem_post(&mutex);

   pthread_exit(0);
}

Output:

USER 1>./thread_sync.exe 10
Sum computed in 1st thread is 55
Sum computed in 2nd thread is 110
sum = 110

Add a comment
Know the answer?
Add Answer to:
so in this code, it computes the sum 1+2+....+n but i want it to compute 2*(1+2+....+n)...
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 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; //...

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

  • I am supposed to write documentation and report for the code below but I am new...

    I am supposed to write documentation and report for the code below but I am new to operating system concepts I will appreciate if someone can help make a detailed comment on each line of code for better understanding. Thanks #include <pthread.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <ctype.h> #define handle_error_en(en, msg) \ do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0) #define handle_error(msg) \ do { perror(msg); exit(EXIT_FAILURE); } while (0) struct thread_info...

  • Read given code RaceOrNot3.c and write all possible outputs of the program. Assume there will be...

    Read given code RaceOrNot3.c and write all possible outputs of the program. Assume there will be no thread creation or joining failures or semaphore failures. If you believe there is only one possible output, you just need to write that output. #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> #include <errno.h> sem_t s1; int c=0,x=0; void *UpdateC1(void *arg) {    int i;    for(i=0;i<2000000;i++)   {        sem_wait(&s1);        c++;   x++;        sem_post(&s1);    } } void *UpdateC2(void *arg) {    int i,x=0;    for(i=0;i<2999999;i++)   {        sem_wait(&s1);        c++;   x++;       ...

  • Read given code and write all possible outputs of the program. Assume there will be no...

    Read given code and write all possible outputs of the program. Assume there will be no thread creation or joining failures or mutex failures. If you believe there i only one possible output, you just need to write that output. Code: #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> #include <errno.h> sem_t s1; int c[2] = {0,1}; void *UpdateC1(void *arg) { int i; for(i=0;i<1000000;i++) { sem_wait(&s1); c[0]=(c[0]+1)%2; c[1]=(c[1]+1)%2; sem_post(&s1); } return NULL; } void *UpdateC2(void *arg) { int i; for(i=0;i<2000000;i++)...

  • Read given code RaceOrNot1.c and write all possible outputs of the program. Assume there will be...

    Read given code RaceOrNot1.c and write all possible outputs of the program. Assume there will be no thread creation or joining failures or mutex failures. If you believe there is only one possible output, you just need to write that output. #include <stdio.h> #include <stdlib.h> #include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t count_mutex3 = PTHREAD_MUTEX_INITIALIZER; int c[2] = {1,0}; void *UpdateC1(void *arg) {    int i;    for(i=0;i<1000000;i++)    {        pthread_mutex_lock(&count_mutex);        c[0]=(c[0]+1)%2;        c[1]=(c[1]+1)%2;        pthread_mutex_unlock(&count_mutex);    }    return NULL; } void *UpdateC2(void *arg) {    int...

  • Please finish the following program /** * Basic POSIX Thread (pthread) Usage 1. * * By...

    Please finish the following program /** * Basic POSIX Thread (pthread) Usage 1. * * By walking through this example you’ll learn: * - How to use pthread_create(). * - How to use pthread_exit(). * - How to use pthread_join(). * */ #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <sys/wait.h> void* ninja(void* arg){ printf("Who’s there?"); fflush(stdout); pthread_exit("ninja"); } // // Expected output: // // Knock knock. // Who's there? - from ninja // Knuc...kles. // int main(int argc, char* argv[]){...

  • Would u help me fixing this CODE With Debugging Code with GDB #include <stdio.h> #include <stdlib.h>...

    Would u help me fixing this CODE With Debugging Code with GDB #include <stdio.h> #include <stdlib.h> #define SIZE (10) typedef struct _debugLab { int i; char c; } debugLab; // Prototypes void PrintUsage(char *); void DebugOption1(void); void DebugOption2(void); int main(int argc, char **argv) { int option = 0; if (argc == 1) { PrintUsage(argv[0]); exit(0); } option = atoi(argv[1]); if (option == 1) { DebugOption1(); } else if (option == 2) { DebugOption2(); } else { PrintUsage(argv[0]); exit(0); } }...

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

  • a multi-threaded producer / consumer program without any locking or signaling. It therefore has synchronization problems....

    a multi-threaded producer / consumer program without any locking or signaling. It therefore has synchronization problems. Add locks and signals so that it works correctly. /* Homework 5.X */ /* Robin Ehrlich */ /* compile: gcc Homework5.c -lpthread */ #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> struct class {    struct class *next;    int id;    int grade; }; #define SLEEP_TIME 1 #define MAX_PRODUCE 10 static struct class *classHead = NULL; static struct class *classTail = NULL; static...

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