CONCEPT OF PTHREADS

Go down

CONCEPT OF PTHREADS

Post  saurabh saxena on Fri Oct 31, 2008 2:04 pm

Pthreads refer to as the POSIX standards defining an API for thread creation and synchronisation.This the specification for thread behaviiour and not an implementation.In a pthread program seperate threads begin execution in specified function.All pthread programs must include header file.
FOR EXAMPLE:-
#include
#include
#include

void *message_print(void *ptr)
{
char *message;
message=(char*)ptr;
printf("\n%s",message);
}


main()
{
pthread_t thread1;
pthread_t thread2;

char *messag1="thread1 is executing";
char *messag2="thread2 is executing";

pthread_create(&thread1,NULL,message_print,(void*)messag1);
pthread_create(&thread2,NULL,message_print,(void*)messag2);

pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
exit(0);
}


In the above example,the program will print first "thread1 is executing",and after that "thread2 is executing".
actually in this program we created two threads thread1 and thread2.
we used pthread_t command:- this command is used to get the thread id,we stored this id in thread1 and thread2 variables.
pthread_create command:- this command is used to create the thread,in this function call we have to supply the thread id,attributes which we have set to NULL i.e default,thread function name,argument to be passed.
pthread_join command:- this command is used to interrupt the main execution and start the thread execution.the main execution will remain interrupted untill the thread execution is completed.

Now there is a question for you In the above the example if we change the order of joining of the threads,what will happen?
i.e.if we write
pthread_join(thread2,NULL);
pthread_join(thread1,NULL);

obviously the executionn order of the threads will change,first the second thread will execute and then the first thread.
avatar
saurabh saxena

Number of posts : 19
Age : 32
Location : pune
Registration date : 2008-08-22

View user profile

Back to top Go down

Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum