Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

POSIX Threads

3,277 views

Published on

POSIX Threads in Linux

Published in: Technology
  • Login to see the comments

POSIX Threads

  1. 1. © 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. POSIX Threads
  2. 2. 2© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. What to Expect? W’s of Threads Single & Multi-threaded Processes Advantages of using threads Creating & Passing data to threads Thread Attributes Thread Cancellation Thread Specific data
  3. 3. 3© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. W’s of Threads Need for the multitasking within the program Event driven programming Thread exists within a process Each thread may be executing a different part of the program at any given time Linux Kernel schedules them asynchronously
  4. 4. 4© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Multi-Process vs Multi-Threaded code data files regs stack ... Parent Process ...code data files regs stack ... Child Process Child Process code data files regs stack ... code data files regs stack ... Main Process regs stack ... Thread regs stack ... Thread
  5. 5. 5© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Threads vs Multiple Processes Threads Advantages Inexpensive Creation & Termination Inexpensive Context Switching Communication is Inherent & Far More As already sharing almost all resources No kernel interaction involved Threads Disadvantages Security because of inherent sharing
  6. 6. 6© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. W's of pthread POSIX standard (IEEE Std 1003.1) thread APIs Defined as “pthread” library with a set of C language programming types C language function calls Prototyped in pthread.h header/include file Library may or may not be part of standard C library On Linux pthread library is not part of libc (libc.so, libc.a) Provided separately as: libpthread.so, libpthread*.a Compiling: gcc -o <out_file> <input_file> -lpthread
  7. 7. 7© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Thread Creation int pthread_create( pthread_t *thread_id, → Id of the thread created const pthread_attr_t *attr, → Thread interaction attributes void *(*start_routine)(void *), → Function to start execution void *arg → Argument to pass any data to thread ); → 0 on success; error code < 0 on error attr = NULL implies default thread attributes Thread exits on return by the *start_routine arg could be used to create different threads with same start function Function returns immediately scheduling both the threads asynchronously
  8. 8. 8© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Thread Termination Thread terminates Normally On start_routine termination By call to pthread_exit(void *exit_val); Abnormally On cancellation Return value / status is a void * Return value from start_routine Or, exit_val Or, PTHREAD_CANCELED
  9. 9. 9© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Waiting for my threads Parent could wait for its threads using int pthread_join(pthread_t tid, void **retval); tid → Id of thread to wait for *retval → Thread exit status, if retval != NULL Returns 0 on success error code < 0 on error Try out: thread_join.c, thread_return.c Observe: thread_unsafe.c
  10. 10. 10© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Not waiting for my threads What if the main thread doesn't join? A clean up of the thread is not guaranteed If main thread quits, process quits All threads in it cease to exist & are cleaned If main thread runs, and don't want to join Creating detached threads is the option By modifying the thread attributes Detached threads can't be joined And they clean up on their termination
  11. 11. 11© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Thread Attributes Provides a mechanism for fine-tuning the behaviour of individual threads Configurable by passing a valid “attr” to pthread_create Before that, pthread_attr_t object needs Initialization: int pthread_attr_init(pthread_attr_t *attr); Modification using various pthread_attr_set* functions And after that, pthread_attr_t object needs Destruction: int pthread_attr_destroy(pthread_attr_t *attr); Have a look @ thread_attr.c
  12. 12. 12© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Let's Detach Threads Attribute Modification Function int pthread_attr_setdetachstate( pthread_attr_t *attr, int detachstate ); detachstate PTHREAD_CREATE_DETACHED PTHREAD_CREATE_JOINABLE Try out: thread_detach.c
  13. 13. 13© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Some Thread Id Functions pthread_t pthread_self(); Returns the id of the current thread Can be used for thread specific variations / data int pthread_equal(pthread_t t1, pthread_t t2) Compares thread ids t1 & t2 Returns non-zero on equal, zero otherwise pthread_join(pthread_self(), NULL); ??? Returns EDEADLK
  14. 14. 14© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Thread Cancellation Terminating other thread int pthread_cancel(pthread_t tid); When & Where the cancelled thread exits? Depends on its cancel state & type attribute These attributes could be set using int pthread_setcancelstate(int state, int *oldstate); int pthread_setcanceltype(int type, int *oldtype); States PTHREAD_CANCEL_DISABLE, PTHREAD_CANCEL_ENABLE Type PTHREAD_CANCEL_DEFERRED, PTHREAD_CANCEL_ASYNCHRONOUS Try out: thread_cancel.c
  15. 15. 15© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Thread Cancellation ... Why Uncancellable? To enable critical section implementations What are Cancellable Points? Calls to certain functions specified by POSIX.1 standards. Refer “man 7 pthreads” for list Deferred Cancellation still doesn't solve Resource Leak during Cancellation Only solution: Cleanup Handler
  16. 16. 16© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Cleanup Handler Specifics Function which gets called when a thread exits either Due to cancellation Call to pthread_exit But not by return of the thread start function Should be called explicitly Typical tasks are cleanups of Thread-specific data keys Memory allocations Mutex waits
  17. 17. 17© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Cleanup Handler ... Registration int pthread_cleanup_push( void (*handler)(void *), → cleanup handler void *arg → argument to the cleanup handler ); Unregistration int pthread_cleanup_pop( int execute → also execute the handler, if non-zero ); These two calls must be balanced Experiment: thread_cancel_cleanup.c
  18. 18. 18© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Thread-Specific Data By default all data is shared (public) Good for inter thread communication But no privacy for a thread Though in some cases it may be desirable An Example Multiple threads to log in their respective files Individual thread needs to store & retrieve Its own log file pointer And so pthreads do support it
  19. 19. 19© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Thread-Specific Data ... Implemented using a thread specific data area In the same Process Address Space Variables in this area are duplicated for each thread But should be accessed with special atomic functions for setting and retrieving values APIs needed int pthread_key_create(pthread_key_t *k, void (*dest)(void *)); int pthread_key_delete(pthread_key_t key); int pthread_setspecific(pthread_key_t key, void *val); void *pthread_getspecific(pthread_key_t key); Let's see the thread_logging.c example
  20. 20. 20© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. What all have we learnt? W’s of Threads Single & Multi-threaded Processes Advantages of using threads Creating & Passing data to threads Thread attributes Thread Cancellation Thread Specific data
  21. 21. 21© 2019 SysPlay Workshops <workshop@sysplay.in> All Rights Reserved. Any Queries?

×