Write a C program to illustrate concurrent execution of threads using pthreads Library

Ram Pothuraju
Specifying Potential Parallelism in a Concurrent Programming Environment
Now that we know the orderings that we desire or would allow in our program, how do we express potential parallelism at the programming level? Those programming environments that allow us to express potential parallelism are known as concurrent programming environments. A concurrent programming environment lets us designate tasks that can run in parallel. It also lets us specify how we would like to handle the communication and synchronization issues that result when concurrent tasks attempt to talk to each other and share data.
Because most concurrent programming tools and languages have been the result of academic research or have been tailored to a particular vendor’s products, they are often inflexible and hard to use. Pthreads, on the other hand, is designed to work across multiple vendors’ platforms and is built on top of the familiar UNIX C programming interface. Pthreads gives you a simple and portable way of expressing multithreading in your programs.



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



void *mythread1(void *vargp)
{
   int i;
   printf("thread1\n");
      for(i=1;i<=10;i++)
     printf("i=%d\n",i);    
   printf("exit from thread1\n");
  return NULL;
}

void *mythread2(void *vargp)
{
    int j;
   printf("thread2 \n");
   for(j=1;j<=10;j++)
    printf("j=%d\n",j);
   
 printf("Exit from thread2\n");
  return NULL;
}


int main()
{
  pthread_t tid;
  printf("before thread\n");
  pthread_create(&tid,NULL,mythread1,NULL);
  pthread_create(&tid,NULL,mythread2,NULL);
  pthread_join(tid,NULL);
  pthread_join(tid,NULL);
  exit(0);
}

OUT PUT :: 

$ cc w8.c – l pthread

$./a.out 
thread1
i=1
i=2;
i=3
thread2
j=1
j=2
j=3
j=4
j=5
j=6
j=7
j=8
i=4
i=5
i=6
i=7
i=8
i=9
i=10
exit from thread1
j=9
j=10
exit from thread2

Post a Comment

0Comments

Post a Comment (0)