Header Ads

Thread Concepts Program


A thread is a flow of execution through the process code, with its own program counter that keeps track of which instruction to execute next, system registers which hold its current working variables, and a stack which contains the execution history.
A thread shares with its peer threads few information like code segment, data segment, and open files. When one thread alters a code segment memory item, all other threads see that.

A thread is also called a lightweight process. Threads provide a way to improve application performance through parallelism. Threads represent a software approach to improving the performance of the operating system by reducing the overhead thread is equivalent to a classical process.

Program 1

Program to create a thread. The thread prints numbers from zero to n, where value of n is passed from the main process to the thread. The main process also waits for the thread to finish first and then prints from 20-24.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include<string.h>
void *thread_function(void *arg); 
int i,n,j;
int main()
{
     char *m="5"; 
     pthread_t a_thread;  //thread declaration
     void *result;
     pthread_create(&a_thread, NULL, thread_function, m); //thread is created
     pthread_join(a_thread, &result); //process waits for thread to finish . Comment this line to see the difference
     printf("Thread joined\n");
     for(j=20;j<25;j++)
                {
                printf("%d\n",j);
                sleep(1);
                }
     printf("thread returned %s\n",result);
}

void *thread_function(void *arg) 
{    // the work to be done by the thread is defined in this function
        int sum=0;
        n=atoi(arg);
        for(i=0;i<n;i++)
                {
                printf("%d\n",i);
                sleep(1);
                }
        pthread_exit("Done"); // Thread returns "Done" 
}


Program 2:

Program to create a thread. The thread is passed more than one input from the main process. For passing multiple inputs we need to create structure and include all the variables that are to be passed in this structure.
#include <stdio.h>
#include <pthread.h>
struct arg_struct {   //structure which contains multiple variables that are to passed as input to the thread
    int arg1;
    int arg2;
};
void *arguments(void *arguments)
{
    struct arg_struct *args=arguments;
    printf("%d\n", args -> arg1);
    printf("%d\n", args -> arg2);
    pthread_exit(NULL);
}
int main()
{
    pthread_t t;
    struct arg_struct args;
    args.arg1 = 5;
    args.arg2 = 7;
    pthread_create(&t, NULL, arguments, &args); //structure passed as 4th argument
    pthread_join(t, NULL); /* Wait until thread is finished */
}


A Practical Thread Example

Following is the example code where we tried to use all the three functions discussed above.

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t tid[2];
void* doSomeThing(void *arg)
{
    unsigned long i = 0;
    pthread_t id = pthread_self();
    if(pthread_equal(id,tid[0]))
    {
        printf("\n First thread processing\n");
    }
    else
    {
        printf("\n Second thread processing\n");
    }
    for(i=0; i<(0xFFFFFFFF);i++);
    return NULL;
}
int main(void)
{
    int i = 0;
    int err;
    while(i < 2)
    {
        err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
        if (err != 0)
            printf("\ncan't create thread :[%s]", strerror(err));
        else
            printf("\n Thread created successfully\n");
        i++;
    }
    sleep(5);
    return 0;
}
So what this code does is :

It uses the pthread_create() function to create two threads
The starting function for both the threads is kept same.
Inside the function ‘doSomeThing()’, the thread uses pthread_self() and pthread_equal() functions to identify whether the executing thread is the first one or the second one as created.
Also, Inside the same function ‘doSomeThing()’ a for loop is run so as to simulate some time consuming work.

Now, when the above code is run, following was the output :

$ ./threads
Thread created successfully
First thread processing
Thread created successfully
Second thread processing




Powered by Blogger.