Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write Program in C not C++ (Should Run On Linux) Use Shared Memory Create thread

ID: 3883665 • Letter: W

Question

Write Program in C not C++ (Should Run On Linux)

Use Shared Memory

Create thread 1 to 12

You should be able to adjust the thread range ( Example: Thread 1 to 12). If the thread is odd then it will compute the tid as a factorial. If the thread is even then it will compute the thread as a summation.

Example 1: Enter thread number: 5

***Refer to odd Below***

Example 2: Enter thread number: 6

***Refer to Even Below***              

                Odd Threads:

                                -compute tid factorial 1*2*3*4*5

                Even Threads:

                                -compute tid summation 1+2+3+4+5+6

Testing: Threads can print

                Final: all output from main

-Main computes sum of the thread values

Display on screen:

               - report each value in the thread

                -report overall sum in threads

Please run and display working program for Odd and Even Threads.

Explanation / Answer

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

struct params {
    pthread_mutex_t mutex;
    int id;
};

typedef struct params params_t;

void * calculate(void * arg) {
int id, factorial = 1, i, sum = 0;
pthread_mutex_lock( & ( * (params_t * )(arg)).mutex);
id = ( * (params_t * )(arg)).id;
if (id % 2 == 1) {
    for (i = 1; i <= id; ++i) {
      factorial *= i;
    }
    pthread_mutex_unlock( & ( * (params_t * )(arg)).mutex);
    printf("Factorial for odd %d : %d ", id, factorial);
} else {
    for (i = id; i > 0; i--) {
      sum = sum + i;
    }
    pthread_mutex_unlock( & ( * (params_t * )(arg)).mutex);
    printf("Sum for even %d : %d ", id, sum);
}

}

int main() {
pthread_t threads[13];
params_t params;
pthread_mutex_init( & params.mutex, NULL);

int i;
while (1) {
    printf(" Enter Thread number between 1 to 12 : ");
    scanf("%d", & i);
    if (i >= 1 && i <= 12) {
      params.id = i;
      if (pthread_create( & threads[i], NULL, calculate, & params));

      pthread_join(threads[i], NULL);
    } else {
      printf(" You have entered wrong thread id.");
    }
}
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote