C Programming Tutorial

 
 
 
 

Image

# include <stdio.h>
# include <pthread.h>

struct parastruct
{
    int from;
    int to;
}*para;


struct node
{
    int no;
    struct node *next;
};

void *createlist_thread(void *parast);

int main()
{
    int iNumber;
    int iCount;
    struct node *list1,*list2,*head;
    pthread_t tid;
    printf(\"Enter Number up to Which you want to Create List :\");
    scanf(\"%d\",&iNumber);

    if(iNumber<=1)
    {
        printf(\"\\nError : Enter Number Greater than 1 \\n\\n\");
    }
    else
    {
        para=(struct parastruct*)malloc(sizeof(struct parastruct));
        para->from=(iNumber/2) + 1;
        para->to=iNumber;
        pthread_create(&tid,NULL,createlist_thread,(void *)para);

        for(iCount=1;iCount<=iNumber/2;iCount++)
        {
            if(iCount==1)
            {
                list1=(struct node*)malloc(sizeof(struct node));
                head=list1;
            }
            else
            {
                list1->next=(struct node*)malloc(sizeof(struct node));
                list1=list1->next;
            }
            list1->no=iCount;
            list1->next=NULL;
        }

        pthread_join(tid,(void**)&list2);


        list1->next=(struct node*)malloc(sizeof(struct node));
        list1->next=list2;

        list1=head;
        printf(\"\\nList Added by Main ...\\n\");
        for(iCount=1;iCount<=iNumber;iCount++)
        {            
            if(iCount==para->from)
            {
                printf(\"\\nList Added by Thread ...\\n\");                            }
            printf(\"%d \\t\",list1->no);
            list1=list1->next;
        }
    }        
    printf(\"\\n\");
    return 0;
}

void *createlist_thread(void *para)
{
    struct parastruct *paralist;
    struct node *list2;
    struct node *head;
    int iCount;
    paralist = (struct parastruct*) para;
    for(iCount=paralist->from;iCount<=paralist->to;iCount++)
    {
        if(iCount==paralist->from)
        {
            list2=(struct node *)malloc(sizeof(struct node));
            head=list2;
        }
        else
        {
            list2->next=(struct node *)malloc(sizeof(struct node));
            list2=list2->next;
        }    
        list2->no=iCount;
        list2->next=NULL;
    }
    list2=head;
    pthread_exit((void*)list2);
}

 
 
Didn't find what you were looking for? Find more on Program to create a singly linked list of numbers using threads