Tuesday, August 13, 2013

First Multi Threaded Program in C

Today i have written my first multithreaded program in C on linux,
It is very easy to write multithreded program using the pthread library..
Let us take a look which function we need to create a multithreded program in c...

The function to create the thread:
int pthread_create(pthread_t *tid,const pthread_attr_t *attr,void *(*func)(void *), void *arg)
Note-Each thread will have its own unique thread ID.

The first argument is the variable where its thread ID will be stored. 
The second argument contains attributes describing the thread. Keep this as NULL now,will explain later.
The third argument is a pointer to the function you want to run as a thread.
The final argument is a pointer to data you want to pass to the function.

Having this information in mind you can write a simple multithreaded program in C...

Let us take a look at a example:
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void* myfunc1(void *ptr)
{
char *msg;
msg= (char*)ptr;
printf("%s started\n",msg);
while(1)
{
printf("In the %s\n",msg);
sleep(1);
}
}
void *myfunc2(void *ptr)
{
char *msg;
msg= (char*)ptr;
printf("%s started\n",msg);
while(1)
{
printf("In the %s\n",msg);
sleep(1);
}
}
int main()
{
pthread_t thread1,thread2;
int val1,val2;
char *msg1="Thread1";
char *msg2="Thread2";
printf("In the main funciton\n");
printf("My first thread program\n");
val1= pthread_create(&thread1,NULL,myfunc1,(void*)msg1);
val2= pthread_create(&thread2,NULL,myfunc2,(void*)msg2);
printf("The value returned by thread1=%d\n",val1);
printf("The value returned by thread2=%d\n",val2);
while(1)
{
printf("in the main function\n");
sleep(1);
}
return 0;
}

No comments:

Post a Comment

Feel free to comment......