Posix thread programming basic example


We start with an example of "hello..world".
First we look at program code without threading that is whole program is act like a single thread.

helloworld.cpp


#include <iostream>
#include <unistd.h>


using namespace std;

void function1();
void function2();

int main()
{
     function1();
     function2();
     return 0;
}

void function1()
{
    cout<<"Hello..."<<endl;
    sleep(2);
}

void function2()
{
    cout<<"World"<<endl;
}
Compiling and running:

 




Download source code from here


Now same program code using threading

twothread.cpp
#include <iostream>
#include <unistd.h>
#include <pthread.h>

using namespace std;

void *function1 (void * argument);
void *function2 (void * argument);

int main (void)
{
   pthread_t t1,t2;

   pthread_create(&t1, NULL, function1,NULL);
   pthread_create(&t2, NULL, function2,NULL);
   sleep(1);

   return 0;
}

void * function1 (void * argument)
{
   cout<<"Hello..."<<endl;
  
 
}

void * function2 (void * argument)
{
   cout<<"World"<<endl;
 
}

Compiling and running:








Download source code from here

Threading simply split our program in threads, each thread acts like its own individual program. If all threads are working in same memory space then they can save extra communication overhead.

By threading we can boost up performance of our program by simply exploiting  the power of dual-core /core-2-duo processors.

As  threads are independent , so when we run our twothread.cpp file it may possible that we get "worldhello..." instead of "Hello....World" which is in case of our single thread program, or without threading. because in that case threaded function2 is executed first. Which function should execute first is decided by OS which is based on available resources and how they are allocated to threaded function.

Description of  parameters for ("pthread_create")

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg);

thread: unique identifier for thread of type pthread_t
attr: This is an object which you can create for the thread with specific attributes for the thread. Can be NULL, if you want to use the default attributes. Will not discuss in this post.
start_routine: the function that the thread has to execute.
arg: Function argument if you don't want to pass an argument, set it to NULL.
returns: 0 on success or some error code.

Share this post and spread the knowledge --->

No comments:

Post a Comment