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 8 thr

ID: 3882977 • Letter: W

Question

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

Use Shared Memory

-Create 8 threads [[east to change 2 to 12]]

-Each thread with tid 1 to 12

               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

                - report each value & Sum

                -report overall sum

Explanation / Answer

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

// A normal C function that is executed as a thread
// when its name is specified in pthread_create()

void *myThreadFun(void *vargp)
{
      while(1)
    {
        printf("I am threadFunction. ");
    }
}

int main()
{
    /*creating thread id*/
    pthread_t tid;
    int ret,sum,fact=1,i;

    /*creating thread*/
    ret=pthread_create(&tid, NULL, &myThreadFun, NULL);d ");
     if(ret==0)
   {
        printf("Thread created successfully. ");
    }
    else
    {
        printf("Thread not created. ");
        return 0;      /*return from main*/
     }
     while(1)
     {
     if(tid%2==0)   /*even threads*/
     {
         sum+=tid;
         printf("Summation of threads=%d",sum);
      }
      else
      {
              for(i=tid;i>=0;i--)
       fact=fact*i;
              printf("Factorial=%d",fact);
       }
       }
   
    while(1)
     {
      printf("I am main function. ");    
     }
    exit(0);
}

To compile a multithreaded program using gcc, we need to link it with the pthreads library. Following is the command used to compile the program.

gfg@ubuntu:~/$ gcc multithread.c -lpthread
gfg@ubuntu:~/$ ./a.out

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