Wednesday, May 12, 2010

Threading in linux

Following is the simple program which creates 2 new threads. It uses pthread library.  To compile use
"gcc filename.c -pthread"

#include
#include
#include

void * run (void * usearg)
{
    int *count;
    struct timespec sleepTime;
    struct timespec remainingSleepTime;
   
    count = (int *)usearg;
    printf("In child:%d\n",*count);
    while(*count <20000)
    {
        printf("%d\t",*count);
        (*count)++;
        sleepTime.tv_sec=0;
        sleepTime.tv_nsec=100;
        nanosleep(&sleepTime,&remainingSleepTime);
    }
    printf("Child thread finished\n");
    return NULL;
}

void * runAnother (void * usearg)
{
    int *count;
    struct timespec sleepTime;
    struct timespec remainingSleepTime;
   
    count = (int *)usearg;
    printf("In child:%d\n",*count);
    while(*count <30000)
    {
        printf("%d\t",*count);
        (*count)++;
        sleepTime.tv_sec=0;
        sleepTime.tv_nsec=100;
        nanosleep(&sleepTime,&remainingSleepTime);
    }
    printf("Child thread finished\n");
    return NULL;
}

int main()
{
    void *retValue;
    pthread_t threadId,threadId1;
    int countThread = 10000,countThread1 = 20000;
    int countMain = 0;
    struct timespec sleepTime;
    struct timespec remainingSleepTime;

    if(pthread_create(&threadId,NULL,run, &countThread)==0 && pthread_create(&threadId1,NULL,runAnother, &countThread1)==0)
    {
        printf("Thread created sucessfully\n");
    }
    else
    {
        perror("Thread could not be created\n");
    }
    while(countMain<10000)
    {
        printf("%d\t",countMain);
        countMain++;
        sleepTime.tv_sec=0;
        sleepTime.tv_nsec=100;
        nanosleep(&sleepTime,&remainingSleepTime);
    }
    printf("Main thread finished\n");
    pthread_join(threadId,&retValue);
    pthread_join(threadId1,&retValue);
    printf("Children Joined\n");
    return 0;
}

No comments:

Post a Comment

Android aar deployment in Maven - 2022

Introduction If you are working on android library project, you might be wondering how to publish it on Maven like this . Earl...