Threads 2

Lab06_Problem02: Write a C program that creates multiple threads with NULL as parameter sent to the thread execution function, runner. Each thread inside the runner function must reads an integer value, n, and then produce sum of values from 1 to n(inclusive) and prints the sum. Ensure that the main() must wait for the termination of these two threads. 

C program demonstrating creation of two threads and termination of both threads before
main function Compile the program using: gcc program_file.c -o program_file -pthread
Run the file using: "./program_file" in ubuntu or linux terminal and enter the value of N twice for
both threads input despite "Enter N" statement will be printed simultaneoulsy on same line due to both
threads executing simultaneously.


  
#include 
#include 
#include 
#include 

void *runner(void *arg)
{
   int N;
   printf("Enter N : ");  
   scanf("%d", &N);
   int sum=(N*(N+1))/2;
   printf("N is : %d\n", sum);
   return NULL;
}

int main()
{
   pthread_t thread_id1, thread_id2;
   printf("Before Thread1 and Thread2 starting\n");
   pthread_create(&thread_id1, NULL, runner, NULL);
   pthread_create(&thread_id2, NULL, runner, NULL);
   pthread_join(thread_id1, NULL);
   pthread_join(thread_id2, NULL);
   printf("After Thread1 and Thread2 are terminated\n");
   exit(0);
}

Previous Post Next Post