Threads
Process Processes contain information about program resources and program execution state, including: Process ID, process group ID, user ID, and group ID Environment Working directory. Program instructions Registers Stack Heap File descriptors Signal actions Shared libraries Inter-process communication tools (such as message queues, pipes, semaphores, or shared memory).
UNIX Process
Threads Threads use and exist within these process resources, yet are able to be scheduled by the operating system and run as independent entities largely because they duplicate only the bare essential resources that enable them to exist as executable code.
Cont. This independent flow of control is accomplished because a thread maintains its own: Stack pointer Registers Scheduling properties (such as policy or priority) Set of pending and blocked signals Thread specific data (thread ID)
UNIX Thread
UNIX Threads In the UNIX environment a thread: Exists within a process and uses the process resources Has its own independent flow of control as long as its parent process exists and the OS supports it Duplicates only the essential resources it needs to be independently schedulable May share the process resources with other threads that act equally independently (and dependently) Dies if the parent process dies - or something similar Is "lightweight" because most of the overhead has already been accomplished through the creation of its process.
Pthreads A thread library that provides the programmer an API for creating and managing threads Pthreads refers to the POSIX standards defining an API for thread creation and synchronization
Pthreads Pthreads are defined as a set of C language programming types and procedure calls, implemented with a pthread.h header/include file and a thread library
Creating threads Initially, your main() program comprises a single, default thread. All other threads must be explicitly created by the programmer.
Creating threads (cont.) int pthread_create (pthread_t * thread , const pthread_attr_t * attr , void *(* start_routine ) (void*), void * arg ); Description: pthread_create() creates a new thread and makes it executable. This routine can be called any number of times from anywhere within your code.
Creating threads (cont.) pthread_create() arguments: thread: An opaque, unique identifier for the new thread returned by the subroutine. attr: An opaque attribute object that may be used to set thread attributes. You can specify a thread attributes object, or NULL for the default values. start_routine: the C routine that the thread will execute once it is created. arg: A single argument that may be passed to start_routine . It must be passed by reference as a pointer cast of type void. NULL may be used if no argument is to be passed.
Cont. Return value: If successful, the pthread_create() routine shall return zero other- wise, an error number shall be returned to indicate the error.
Thread attributes Thread attributes include (define members of the struct pthread_attr_t): detached state scheduling policy scheduling parameter inheritsched attribute Scope guard size stack address stack size
Scheduling threads After a thread has been created, how do you know when it will be scheduled to run by the operating system? It is up to the implementation and/or operating system to decide where and when threads will execute.
Terminating threads pthread_exit() is used to explicitly exit a thread. If main() finishes before the threads it has created, and exits with pthread_exit() , the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes.
Joining Threads int pthread_join (pthread_t thread, void **value_ptr); Description: The pthread_join() function shall suspend execution of the calling thread until the target thread terminates. Return value: If successful, the pthread_join() function shall return zero; otherwise, an error number shall be returned to indicate the error.
Joining Threads (Cont.)
Example -1-
#include <pthread.h> #include <stdio.h> #define NUM_THREADS 5 void *PrintHello(void *threadid) { int tid; tid = (int)threadid; printf(&quot;Hello World! It's me, thread #%d!\n&quot;, tid); pthread_exit(NULL); } int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc, t; for(t=0; t<NUM_THREADS; t++){ printf(&quot;In main: creating thread %d\n&quot;, t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); if (rc){ printf(&quot;ERROR; return code from pthread_create() is %d\n&quot;, rc); exit(-1); } } pthread_exit(NULL);}
Code Explanation
Defines an array of threads (note: threads are not yet created!) of opaque type pthread_t In for loop: Threads will be created using pthread_create . The routine PrintHello() is the starting routine for all newly created threads The returned value for each thread creation will be checked and prints and error message if the returned value is not zero int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc, t; for(t=0; t<NUM_THREADS; t++){ printf(&quot;In main: creating thread %d\n&quot;, t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); if (rc){ printf(&quot;ERROR; return code from pthread_create() is %d\n&quot;, rc); exit(-1); } }
Cont. The routine PrintHello will simply print, “ Hello World! It’s me, thread# threadnum It will then terminate the thread using pthread_exit. void *PrintHello(void *threadid) { int tid; tid = (int)threadid; printf(&quot;Hello World! It's me, thread #%d!\n&quot;, tid); pthread_exit(NULL); }
Possible Outputs In main: creating thread 0 In main: creating thread 1 Hello World! It's me, thread#0! In main: creating thread 2 Hello World! It's me, thread #1! Hello World! It's me, thread #2! In main: creating thread 3 In main: creating thread 4 Hello World! It's me, thread #3! Hello World! It's me, thread #4! In main: creating thread 0 In main: creating thread 1 In main: creating thread 2 In main: creating thread 3 In main: creating thread 4 Hello World! It's me, thread#0! Hello World! It's me, thread #1! Hello World! It's me, thread #2! Hello World! It's me, thread #3! Hello World! It's me, thread #4!
Example -2-
#include <stdio.h> #include <stdlib.h> #include <pthread.h> void *print_message_function( void *ptr ); main() { pthread_t thread1, thread2; char *message1 = &quot;Thread 1&quot;; char *message2 = &quot;Thread 2&quot;; int iret1, iret2; /* Create independent threads each of which will execute function */ iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1); iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2); /* Wait till threads are complete before main continues. Unless we */ /* wait we run the risk of executing an exit which will terminate */ /* the process and all threads before the threads have completed. */ pthread_join( thread1, NULL); pthread_join( thread2, NULL); printf(&quot;Thread 1 returns: %d\n&quot;,iret1); printf(&quot;Thread 2 returns: %d\n&quot;,iret2); exit(0); } void *print_message_function( void *ptr ) { char *message; message = (char *) ptr; printf(&quot;%s \n&quot;, message); }
Code Explanation
Defines an array of threads (note: threads are not yet created!) of opaque type pthread_t Threads will be created using pthread_create() . The routine print_message_function() is the starting routine for the two newly created routines. Notice that an argument was sent to print_message_function() as an argument to pthread_create() The two threads newly created will be joined using pthread_join() main() { pthread_t thread1, thread2; char *message1 = &quot;Thread 1&quot;; char *message2 = &quot;Thread 2&quot;; int iret1, iret2; iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1); iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2); pthread_join( thread1, NULL); pthread_join( thread2, NULL); printf(&quot;Thread 1 returns: %d\n&quot;,iret1); printf(&quot;Thread 2 returns: %d\n&quot;,iret2); exit(0); }
Cont. The routine PrintHello will simply print, “ Hello World! It’s me, thread# threadnum It will then terminate the thread using pthread_exit. void * print_message_function( void *ptr ) { char *message; message = (char *) ptr; printf\n&quot;, message); } (&quot;%s
Output Thread 1 Thread 2 Thread 1 returns : 0 Thread 2 returns : 0
Example -3- Example 1 while using pthread_join()
#include <pthread.h> #include <stdio.h> #define NUM_THREADS 5 void *PrintHello(void *threadid) { int tid; tid = (int)threadid; printf(&quot;Hello World! It's me, thread #%d!\n&quot;, tid); pthread_exit(NULL); } int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc, t; for(t=0; t<NUM_THREADS; t++){ printf(&quot;In main: creating thread %d\n&quot;, t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); if (rc){ printf(&quot;ERROR; return code from pthread_create() is %d\n&quot;, rc); exit(-1); } pthread_join(threads[t], NULL) ;} pthread_exit(NULL);}
Possible Outputs In main: creating thread 0 Hello World! It's me, thread#0! In main: creating thread 1 Hello World! It's me, thread #1! In main: creating thread 2 Hello World! It's me, thread #2! In main: creating thread 3 Hello World! It's me, thread #3! In main: creating thread 4 Hello World! It's me, thread #4!
Example -4-
#include <pthread.h> #include <stdlib.h> #include <stdio.h> void *thread_func( void *vptr_args ); int main( void ){ int i, j; pthread_t thread; pthread_create( &thread, NULL, &thread_func, NULL ); for( j= 0; j < 6; ++j ){ fprintf( stdout, &quot;a\n&quot; ); for( i= 99999999; i; --i ); /* use some CPU time */ } pthread_join( thread, NULL ); exit( EXIT_SUCCESS ); } void *thread_func( void *vptr_args ){ int i, j; for( j= 0; j < 6; ++j ){ fprintf( stderr, &quot; b\n&quot; ); for( i= 99999999; i; --i ); /* use some CPU time */ } return NULL; }
Output a b a a b a b a b b a b What happens if we change the position of pthread_join() in the code?
#include <pthread.h> #include <stdlib.h> #include <stdio.h> void *thread_func( void *vptr_args ); int main( void ){ int i, j; pthread_t thread; pthread_create( &thread, NULL, &thread_func, NULL ); pthread_join( thread, NULL ); for( j= 0; j < 6; ++j ){ fprintf( stdout, &quot;a\n&quot; ); for( i= 99999999; i; --i ); /* use some CPU time */ } /* Previous position in code pthread_join( thread, NULL ); */ exit( EXIT_SUCCESS ); } void *thread_func( void *vptr_args ){ int i, j; for( j= 0; j < 6; ++j ){ fprintf( stderr, &quot; b\n&quot; ); for( i= 99999999; i; --i ); /* use some CPU time */ } return NULL; }
Output b b b b b b a a a a a a What happened?

Tutorial4 Threads

  • 1.
  • 2.
    Process Processes containinformation about program resources and program execution state, including: Process ID, process group ID, user ID, and group ID Environment Working directory. Program instructions Registers Stack Heap File descriptors Signal actions Shared libraries Inter-process communication tools (such as message queues, pipes, semaphores, or shared memory).
  • 3.
  • 4.
    Threads Threads useand exist within these process resources, yet are able to be scheduled by the operating system and run as independent entities largely because they duplicate only the bare essential resources that enable them to exist as executable code.
  • 5.
    Cont. This independentflow of control is accomplished because a thread maintains its own: Stack pointer Registers Scheduling properties (such as policy or priority) Set of pending and blocked signals Thread specific data (thread ID)
  • 6.
  • 7.
    UNIX Threads Inthe UNIX environment a thread: Exists within a process and uses the process resources Has its own independent flow of control as long as its parent process exists and the OS supports it Duplicates only the essential resources it needs to be independently schedulable May share the process resources with other threads that act equally independently (and dependently) Dies if the parent process dies - or something similar Is &quot;lightweight&quot; because most of the overhead has already been accomplished through the creation of its process.
  • 8.
    Pthreads Athread library that provides the programmer an API for creating and managing threads Pthreads refers to the POSIX standards defining an API for thread creation and synchronization
  • 9.
    Pthreads Pthreads aredefined as a set of C language programming types and procedure calls, implemented with a pthread.h header/include file and a thread library
  • 10.
    Creating threads Initially,your main() program comprises a single, default thread. All other threads must be explicitly created by the programmer.
  • 11.
    Creating threads (cont.)int pthread_create (pthread_t * thread , const pthread_attr_t * attr , void *(* start_routine ) (void*), void * arg ); Description: pthread_create() creates a new thread and makes it executable. This routine can be called any number of times from anywhere within your code.
  • 12.
    Creating threads (cont.)pthread_create() arguments: thread: An opaque, unique identifier for the new thread returned by the subroutine. attr: An opaque attribute object that may be used to set thread attributes. You can specify a thread attributes object, or NULL for the default values. start_routine: the C routine that the thread will execute once it is created. arg: A single argument that may be passed to start_routine . It must be passed by reference as a pointer cast of type void. NULL may be used if no argument is to be passed.
  • 13.
    Cont. Return value:If successful, the pthread_create() routine shall return zero other- wise, an error number shall be returned to indicate the error.
  • 14.
    Thread attributes Threadattributes include (define members of the struct pthread_attr_t): detached state scheduling policy scheduling parameter inheritsched attribute Scope guard size stack address stack size
  • 15.
    Scheduling threads Aftera thread has been created, how do you know when it will be scheduled to run by the operating system? It is up to the implementation and/or operating system to decide where and when threads will execute.
  • 16.
    Terminating threads pthread_exit() is used to explicitly exit a thread. If main() finishes before the threads it has created, and exits with pthread_exit() , the other threads will continue to execute. Otherwise, they will be automatically terminated when main() finishes.
  • 17.
    Joining Threads int pthread_join (pthread_t thread, void **value_ptr); Description: The pthread_join() function shall suspend execution of the calling thread until the target thread terminates. Return value: If successful, the pthread_join() function shall return zero; otherwise, an error number shall be returned to indicate the error.
  • 18.
  • 19.
  • 20.
    #include <pthread.h> #include<stdio.h> #define NUM_THREADS 5 void *PrintHello(void *threadid) { int tid; tid = (int)threadid; printf(&quot;Hello World! It's me, thread #%d!\n&quot;, tid); pthread_exit(NULL); } int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc, t; for(t=0; t<NUM_THREADS; t++){ printf(&quot;In main: creating thread %d\n&quot;, t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); if (rc){ printf(&quot;ERROR; return code from pthread_create() is %d\n&quot;, rc); exit(-1); } } pthread_exit(NULL);}
  • 21.
  • 22.
    Defines an arrayof threads (note: threads are not yet created!) of opaque type pthread_t In for loop: Threads will be created using pthread_create . The routine PrintHello() is the starting routine for all newly created threads The returned value for each thread creation will be checked and prints and error message if the returned value is not zero int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc, t; for(t=0; t<NUM_THREADS; t++){ printf(&quot;In main: creating thread %d\n&quot;, t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); if (rc){ printf(&quot;ERROR; return code from pthread_create() is %d\n&quot;, rc); exit(-1); } }
  • 23.
    Cont. The routinePrintHello will simply print, “ Hello World! It’s me, thread# threadnum It will then terminate the thread using pthread_exit. void *PrintHello(void *threadid) { int tid; tid = (int)threadid; printf(&quot;Hello World! It's me, thread #%d!\n&quot;, tid); pthread_exit(NULL); }
  • 24.
    Possible Outputs Inmain: creating thread 0 In main: creating thread 1 Hello World! It's me, thread#0! In main: creating thread 2 Hello World! It's me, thread #1! Hello World! It's me, thread #2! In main: creating thread 3 In main: creating thread 4 Hello World! It's me, thread #3! Hello World! It's me, thread #4! In main: creating thread 0 In main: creating thread 1 In main: creating thread 2 In main: creating thread 3 In main: creating thread 4 Hello World! It's me, thread#0! Hello World! It's me, thread #1! Hello World! It's me, thread #2! Hello World! It's me, thread #3! Hello World! It's me, thread #4!
  • 25.
  • 26.
    #include <stdio.h> #include<stdlib.h> #include <pthread.h> void *print_message_function( void *ptr ); main() { pthread_t thread1, thread2; char *message1 = &quot;Thread 1&quot;; char *message2 = &quot;Thread 2&quot;; int iret1, iret2; /* Create independent threads each of which will execute function */ iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1); iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2); /* Wait till threads are complete before main continues. Unless we */ /* wait we run the risk of executing an exit which will terminate */ /* the process and all threads before the threads have completed. */ pthread_join( thread1, NULL); pthread_join( thread2, NULL); printf(&quot;Thread 1 returns: %d\n&quot;,iret1); printf(&quot;Thread 2 returns: %d\n&quot;,iret2); exit(0); } void *print_message_function( void *ptr ) { char *message; message = (char *) ptr; printf(&quot;%s \n&quot;, message); }
  • 27.
  • 28.
    Defines an arrayof threads (note: threads are not yet created!) of opaque type pthread_t Threads will be created using pthread_create() . The routine print_message_function() is the starting routine for the two newly created routines. Notice that an argument was sent to print_message_function() as an argument to pthread_create() The two threads newly created will be joined using pthread_join() main() { pthread_t thread1, thread2; char *message1 = &quot;Thread 1&quot;; char *message2 = &quot;Thread 2&quot;; int iret1, iret2; iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1); iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2); pthread_join( thread1, NULL); pthread_join( thread2, NULL); printf(&quot;Thread 1 returns: %d\n&quot;,iret1); printf(&quot;Thread 2 returns: %d\n&quot;,iret2); exit(0); }
  • 29.
    Cont. The routinePrintHello will simply print, “ Hello World! It’s me, thread# threadnum It will then terminate the thread using pthread_exit. void * print_message_function( void *ptr ) { char *message; message = (char *) ptr; printf\n&quot;, message); } (&quot;%s
  • 30.
    Output Thread 1Thread 2 Thread 1 returns : 0 Thread 2 returns : 0
  • 31.
    Example -3- Example1 while using pthread_join()
  • 32.
    #include <pthread.h> #include<stdio.h> #define NUM_THREADS 5 void *PrintHello(void *threadid) { int tid; tid = (int)threadid; printf(&quot;Hello World! It's me, thread #%d!\n&quot;, tid); pthread_exit(NULL); } int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc, t; for(t=0; t<NUM_THREADS; t++){ printf(&quot;In main: creating thread %d\n&quot;, t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); if (rc){ printf(&quot;ERROR; return code from pthread_create() is %d\n&quot;, rc); exit(-1); } pthread_join(threads[t], NULL) ;} pthread_exit(NULL);}
  • 33.
    Possible Outputs Inmain: creating thread 0 Hello World! It's me, thread#0! In main: creating thread 1 Hello World! It's me, thread #1! In main: creating thread 2 Hello World! It's me, thread #2! In main: creating thread 3 Hello World! It's me, thread #3! In main: creating thread 4 Hello World! It's me, thread #4!
  • 34.
  • 35.
    #include <pthread.h> #include<stdlib.h> #include <stdio.h> void *thread_func( void *vptr_args ); int main( void ){ int i, j; pthread_t thread; pthread_create( &thread, NULL, &thread_func, NULL ); for( j= 0; j < 6; ++j ){ fprintf( stdout, &quot;a\n&quot; ); for( i= 99999999; i; --i ); /* use some CPU time */ } pthread_join( thread, NULL ); exit( EXIT_SUCCESS ); } void *thread_func( void *vptr_args ){ int i, j; for( j= 0; j < 6; ++j ){ fprintf( stderr, &quot; b\n&quot; ); for( i= 99999999; i; --i ); /* use some CPU time */ } return NULL; }
  • 36.
    Output a ba a b a b a b b a b What happens if we change the position of pthread_join() in the code?
  • 37.
    #include <pthread.h> #include<stdlib.h> #include <stdio.h> void *thread_func( void *vptr_args ); int main( void ){ int i, j; pthread_t thread; pthread_create( &thread, NULL, &thread_func, NULL ); pthread_join( thread, NULL ); for( j= 0; j < 6; ++j ){ fprintf( stdout, &quot;a\n&quot; ); for( i= 99999999; i; --i ); /* use some CPU time */ } /* Previous position in code pthread_join( thread, NULL ); */ exit( EXIT_SUCCESS ); } void *thread_func( void *vptr_args ){ int i, j; for( j= 0; j < 6; ++j ){ fprintf( stderr, &quot; b\n&quot; ); for( i= 99999999; i; --i ); /* use some CPU time */ } return NULL; }
  • 38.
    Output b bb b b b a a a a a a What happened?