The following code demonstrates creation of threads
using POSIX thread libraries in Linux environment.
Here the pthread_create()
function is used to create child threads along with following parameters:
#include <pthread.h>
#include <stdlib.h>
#include<stdio.h>
///////function for thread-1 /////////////
void *new_thread1(void *thread_args)
{
int i,j;
for
(j=0;j<10;j++)
{
printf("am
in new thread-1\n");
for(i=0;i<500000000;i++);
}
return
NULL;
}
///////function for thread-2 /////////////
void
*new_thread2(void *thread_args)
{
int i,j;
for (j=0;j<10;j++)
{
printf("am in new
thread-2\n");
for(i=0;i<500000000;i++);
}
return NULL;
}
///////main thread /////////////
int main()
{
int i,j;
pthread_t
tcb1, tcb2;
if
(pthread_create( &tcb1, NULL, new_thread1, NULL))
{
printf("error\n");
return
-1;
}
if
(pthread_create( &tcb2, NULL, new_thread2, NULL))
{
printf("error\n");
return -1;
}
for(j=0;j<10;j++)
{
printf("am
in main thread\n");
for(i=0;i<800000000;i++);
}
pthread_join(tcb1,
NULL);
pthread_join(tcb2,
NULL);
return
1;
}
·
tcb: a structure which holds fields of the newly created
thread (tcb1).
·
task_function: pointer to a function which does the actually
task of the child thread (new_thread1).
The pthread_join
function monitors the termination of child threads and returning the control to
parent thread.
The above code (tth.c) can be compiled and executed
as follows:
gcc
tth.c tth.o –lpthread
./tth
Working of the above code is as below:
No comments:
Post a Comment