Online Labs

Thread

 

Multiple strands of execution in a single program are called threads or thread is a sequences of control within a process.Thread proces include thread creation, termination, synchronization (joins,blocking), scheduling and process interaction.All threads within a process share the same addresss space.

A thread in computer science is short for a thread of execution. Threads are a way for a program to fork (or split) itself into two or more simultaneously (or pseudo-simultaneously) running tasks. Threads and processes differ from one operating system to another, but in general, the way that a thread is created and shares its resources is different from the way a process does.

Multiple threads can be executed in parallel on many computer systems. This multithreading generally occurs by time slicing, wherein a single processor switches between different threads, in which case the processing is not literally simultaneous, for the single processor is only really doing one thing at a time. This switching can happen so fast as to give the illusion of simultaneity to an end user.

     Threads are distinguished from traditional multi-tasking operating system processes in that processes are typically independent, carry considerable state information, have separate address spaces, and interact only through system-provided inter-process communication mechanisms. Multiple threads, on the other hand, typically share the state information of a single process, and share memory and other resources directly. Context switching between threads in the same process is typically faster than context switching between processes. Systems like Windows NT and OS/2 are said to have “cheap” threads and “expensive” processes; in other operating systems there is not so great a difference.

Thread Basics

  • Thread operations include thread creation, termination, synchronization (joins,blocking), scheduling, data management and process interaction.
  • A thread does not maintain a list of created threads, nor does it know the thread that created it.
  • All threads within a process share the same address space.
  • Threads in the same process share:
    • Process instructions
    • Most data
    • open files (descriptors)
    • signals and signal handlers
    • current working directory
    • User and group id
  • Each thread has a unique:
    • Thread ID
    • set of registers, stack pointer
    • stack for local variables, return addresses
    • signal mask
    • priority
    • Return value: errno
  • pthread functions return “0” if OK.

Thread Creation

Function call : pthread_create

int pthread_create(pthread_t*thread,pthread_attr_t*attr,void *(*start_routine)

(void*),void *arg);

 Arguments

->thread   – returns the thread id.(unsigned long int defined in bits/pthreadtypes.h)

->attr-Set to NULL if default thread attributes are used.(else define members of the struct pthread_attr_t defined in bits/pthreadtypes.h). Attributes include:

  • detached state(joinable? Default: PTHREAD_CREATE_JOINABLE.Other option:PTHREAD_CREATE_DETACHED)
  • schedulingpolicy(realtime?PTHREAD_INHERIT_SCHED,PTHREAD_EXPLICIT_SCHED,SCHED_OTHER)
  • scheduling parameter
  • inheritsched attribute(Default:PTHREAD_EXPLICIT_SCHED,inherit from parent thread:PTHREAD_INHERIT_SCHED)
  • scope(Kernelthreads:PTHREAD_SCOPE_SYSTEM user threads        PTHREAD_SCOPE_PROCESS, pick one or the other not both)
  • guard size
  • stack address
  • stack size(default minimum PTHREAD_STACK_SIZE set in pthread.h)

->void *(start_routine)-pointer to the function to be threaded.Function has a single argument:pointer to void.

->*arg-pointer to argument of function. To pass multiple arguments,sent a pointer to the structure.   

Termination Of Thread

Function call: pthread_exit

void pthread_exit(void *retval);

Arguments

retval – return value of the thread.

This routine kills the thread.The pthread _exit never returns. If the thread is not detached the thread id and return value may be examined from another thread by using pthread_join.

Thread Synchronization

The thread libraries provide three synchronization mechanisms

  • mutexes – Mutual exclusion lock: Block access to variable by other threads. This enforces exclusive access by thread to a variable or set of variables.
  • joins–Make  athread wait till others are complete(terminated).
  • conditions variables- data type pthread_cond_t.

If implemented correctly then threads have some advantages of (multi) processes, They take:

·                     Less time to create a new thread than a process, because the newly created thread uses the current process address space.

·                     Less time to terminate a thread than a process.

·                     Less time to switch between two threads within the same process, partly because the newly created thread uses the current process address space.

·                     Less communication overheads — communicating between the threads of one process is simple because the threads share everything: address space, in particular. So, data produced by one thread is immediately available to all the other threads.

POSIX Threads is a POSIX standard for threads. The standard defines an API for creating and manipulating threads.

Libraries implementing the POSIX Threads standard are often named Pthreads. Pthreads are most commonly used on POSIX systems such as Linux and Unix,

Program

/*Program for the creation of Algorithm

1. Start.

2. Provide function prototype and definition for the function that is used as thread.

3. Declare variables for storing the thread id and thread attributes.

4. Initialise the thread attributes.

5. Create the thread.

6. Call the thread for execution.

7. Wait for the thread to execute.

8. Stop.

simple thread created in a non detached manner.

* This program illustrates the manner in which a thread can be created from within    

   the main() function.

* This program creates a thread called ‘add’ which accepts two integer values from    

   the user and prints the sum of it.

*  NOTE:->This program should be compiled using the command ‘cc                                                       simplethread.c -lpthread’ and executed using ‘./a.out’.

*/                                                             //inculsion part

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

void* add(void*);                                //prototype of the thread function.

int main()                                             //main function (return type should be int in linux).    

{

int error;                                               //variable to check error (optional)

pthread_t thread_id;                             //variable to store thread id.

pthread_attr_t thread_attribute;           //variable to store properties of thread.

pthread_attr_init(&thread_attribute);  //function call for setting the default properties.

error=pthread_create(&thread_id,&thread_attribute,add,NULL);  //function for thread                         

                                                                                                           creation.

                                                             //error checking (optional)

 if(error!=0)

 {

  printf(“\nError in thread creation.\n”);

  exit(0);

 }

error=pthread_join(thread_id,NULL);      //function for thread calling.

//error checking (optional)

if(error!=0)                                                        

 {  printf(“\nError in thread joining.\n”);

    exit(0);

 }

}                                                                    //function definition for the thread function.

void * add(void *args)

{ int a,b;

 printf(“\nEnter the first number.\n”);

 scanf(“%d”,&a);

 printf(“\nEnter the second number.\n”);

 scanf(“%d”,&b);

 printf(“\nThe sum is:\t%d\n”,a+b);

}

 

Output

 

 

 1

 

 

 

 

 

MULTIPLE THREAD

 

Algorithm

 

1. Start.

2. Provide function prototype and definition for the function that has to be used as thread.

3. Declare the variables for storing the thread id and thread attributes as required    

   depending on the no: of threads to be created.

4. Initialize the thread attribute variables to their default values.

5. Set detach property of the thread.

6. Create the threads as required.

7. Wait for the thread to execute.

8. Stop.

 

Program

//Inculsion part.

 

#include<stdio.h>

#include<pthread.h>

                                                            //function prototype.

void * add(void *);

                                                            //Variable to count the executed thread.

int end;

                                                            //main function.

int main()

{

 pthread_t tid1,tid2;

 pthread_attr_t attribute;

 

 pthread_attr_init(&attribute);

                                                             //function to set detach property of the thread.

 pthread_attr_setdetachstate(&attribute,PTHREAD_CREATE_DETACHED);

 

 pthread_create(&tid1,&attribute,add,(void *)1);

 pthread_create(&tid2,&attribute,add,(void*)2);

 

                                                            //to wait for the thread to finish execution.

 while(end<2)

 {

 }

}

 

                                                            //function prototype for the thread function.

void * add(void * args)

{

 int a,b;

 printf(“\nEntered into %d thread\n”,args);

 

 printf(“\nEnter the first number for thread %d\n”,args);

 scanf(“%d”,&a);

 

 printf(“\nEnter the second number for thread %d\n”,args);

 scanf(“%d”,&b);

 

 printf(“The sum computed by thread %d:\t%d\n”,args,a+b);

 end++;

}

 

 

Output

 2

 

 

 

 

 

DYNAMIC MULTITHREAD CREATION

 Algorithm

 

1. Start.

2. Provide the function prototype and definition for the function that              

    has to be used as thread.

3. Declare variables to store the thread id and thread attributes.

4. Accept the no. of threads from the user.

5. Create the threads by suitably initialising the thread variables.

6. Wait until the threads execute.

7. Stop.

 

Program

 

/*Program to describe dynamic multiple thread creation and passing arguments to it.

 

* This program illustrates the steps involved in creating multiple threads dynamically.

 

* This program accepts the number of threads from the user and creates it at run time.

 

* The procedure is similar to that we used to create multiple threads.

 

NOTE:->This module can be compiled using the command ‘cc dynamic multithread creation.c -lpthread’ and executed using  ‘./a.out’

 

 

 

 

                                                            //inculsion.

#include<stdio.h>

#include<pthread.h>

                                                            //function prototype.

void * thread_function(void *args[]);

 

                                    //variable to know the end of threads execution.

int end;

int main()

{

 int i,count,j;

 int args[2];

 

 pthread_attr_t attribute;

 pthread_t tid;

 

 pthread_attr_init(&attribute);

 pthread_attr_setdetachstate(&attribute,PTHREAD_CREATE_DETACHED);

 

                                    //for accepting the number of threads to be created.

 printf(“\nEnter the number of threads.\n”);

 scanf(“%d”,&count);

 

 for(i=0,j=count;i<count;i++,j–)

 {

                                    //inserting the arguments for the thread

  args[0]=i+1;

  args[1]=j;

 

  printf(“\n\t\tCreating thread %d.\n”,i+1);

 

  pthread_create(&tid,&attribute,(void *)thread_function,(void *)args);

  printf(“\n\t\tCreated thread %d\n”,i+1);

  sleep(1);

 }

                                                            //waiting for the thread execution.

 while(end!=count)

 {

 }

}

                                                            //function definition.

void * thread_function(void *args[])

{

 int a,b;

 

 a=(int)args[0];

 b=(int)args[1];

 printf(“\n\t\tEntered into %d thread.\n”,a);

 

 printf(“\nFirst value obtained from main function:\t%d\n”,a);

 printf(“\nSecond value obtained from main function:\t%d\n”,b);

 end++;

}

 

 

 

 

Output

31

 

 

 

 

 

 

 

 

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: