How to do it…

  1. Define two variables of the type pthread_t to store two thread identifiers:
pthread_t tid1, tid2;
  1. Invoke the pthread_create function twice to create two threads, and assign the identifiers that we created in the previous step. The two threads are created with the default attributes. Specify two respective functions that need to be executed for the two threads:
pthread_create(&tid1,NULL,runThread1,NULL);
pthread_create(&tid2,NULL,runThread2,NULL);
  1. In the function of the first thread, display a text message to indicate that the first thread was created and is running:
printf("Running Thread 1
");
  1. To indicate the execution of the first thread, execute a for loop in the first function to display the sequence of numbers from 1 to 5. To distinguish from the second thread, the sequence of numbers that were generated by the first thread are prefixed by Thread 1:
for(i=1;i<=5;i++)
printf("Thread 1 - %d ",i);
  1. Similarly, in the second thread, display a text message to inform that the second thread has also been created and is running:
  printf("Running Thread 2
");
  1. Again, in the second function, execute a for loop to display the sequence of numbers from 1 to 5. To differentiate these numbers from the ones generated by thread1, this sequence of numbers will be preceded by the text Thread 2:
for(i=1;i<=5;i++)
printf("Thread 2 - %d ",i);
  1. Invoke the pthread_join twice, and pass the thread identifiers we created in step 1 to it. pthread_join will make the two threads, and the main method will wait until both of the threads have completed their tasks:
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
  1. When both of the threads are finished, a text message will be displayed to confirm this:
printf("Both threads are over
");

The twothreads.c program for creating two threads and making them work on independent resources is as follows:

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

void *runThread1(void *arg){
int i;
printf("Running Thread 1 ");
for(i=1;i<=5;i++)
printf("Thread 1 - %d ",i);
}

void *runThread2(void *arg){
int i;
printf("Running Thread 2 ");
for(i=1;i<=5;i++)
printf("Thread 2 - %d ",i);
}

int main(){
pthread_t tid1, tid2;
pthread_create(&tid1,NULL,runThread1,NULL);
pthread_create(&tid2,NULL,runThread2,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
printf("Both threads are over ");
return 0;
}

Now, let's go behind the scenes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset