Thursday, February 11, 2016

Threading in C example

#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
pthread_t tid,tid1;
    void* myfunction(void *arg)
    {   
    int ctr=0;
    for(ctr=1;ctr<=5;ctr++)
    {
    printf("Inside First Thread ctr=%d\n",ctr);
    sleep(5);
    }
    printf("Child thread completed ");
    return NULL;
    }
        void* myfunction1(void *arg)
        {   
        int ctr=0;
        for(ctr=1;ctr<=5;ctr++)
        {
        printf("Inside Second Thread ctr=%d\n",ctr);
        sleep(10);
        }
        printf("Child thread completed");
        return NULL;
        }
    int main()
    {
    int ctr,err,err1;
    err=pthread_create(&tid,NULL,&myfunction,NULL);
    if(err)
    {
    printf("Error in creating thread:%s",strerror(err));
    return 1;
    }
    err1=pthread_create(&tid1,NULL,&myfunction1,NULL);
    if(err1)
    {
    printf("Error in creating thread:%s",strerror(err1));
    return 1;
    }
    for(ctr=0;ctr<=5;ctr++)
    {
    printf("Insidse main thread :ctr=%d\n",ctr);
    }
    printf("Main Thread completed");
    }

No comments:

Post a Comment