Thread-Safe Programming Living With Linux. Thread-Safe Programming Tommy Reynolds Fedora Documentation Project Steering Committee

Slides:



Advertisements
Similar presentations
CS Lecture 4 Programming with Posix Threads and Java Threads George Mason University Fall 2009.
Advertisements

Pthreads & Concurrency. Acknowledgements  The material in this tutorial is based in part on: POSIX Threads Programming, by Blaise Barney.
Multi-core Programming Programming with Posix Threads.
Silberschatz, Galvin and Gagne ©2009Operating System Concepts – 8 th Edition Chapter 4: Threads.
PTHREADS These notes are from LLNL Pthreads Tutorial
Computer Architecture II 1 Computer architecture II Programming: POSIX Threads OpenMP.
3.5 Interprocess Communication
8-1 JMH Associates © 2004, All rights reserved Windows Application Development Chapter 10 - Supplement Introduction to Pthreads for Application Portability.
Lecture 18 Threaded Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
Threads© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department.
Chapter 4: Threads Adapted to COP4610 by Robert van Engelen.
Netprog Threads Programming1 Threads Programming Refs: Chapter 23.
THREAD IMPLEMENTATION For parallel processing. Steps involved Creation Creates a thread with a thread id. Detach and Join All threads must be detached.
Pthread (continue) General pthread program structure –Encapsulate parallel parts (can be almost the whole program) in functions. –Use function arguments.
Operating Systems Yasir Kiani. 22-Sep Agenda for Today Review of previous lecture Process management commands: bg, fg, ^Z, jobs, ^C, kill Thread.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 4: Threads Changes by MA Doman 2013.
Chapter 4: Threads. 4.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts Threads A thread (or lightweight process) is a basic unit of CPU.
Introduction to Pthreads. Pthreads Pthreads is a POSIX standard for describing a thread model, it specifies the API and the semantics of the calls. Model.
The University of Adelaide, School of Computer Science
Today’s topic Pthread Some materials and figures are obtained from the POSIX threads Programming tutorial at
June-Hyun, Moon Computer Communications LAB., Kwangwoon University Chapter 26 - Threads.
CS 346 – Chapter 4 Threads –How they differ from processes –Definition, purpose Threads of the same process share: code, data, open files –Types –Support.
Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design.
Threads and Thread Control Thread Concepts Pthread Creation and Termination Pthread synchronization Threads and Signals.
ICS 145B -- L. Bic1 Project: Process/Thread Synchronization Textbook: pages ICS 145B L. Bic.
CS345 Operating Systems Threads Assignment 3. Process vs. Thread process: an address space with 1 or more threads executing within that address space,
Programming with POSIX* Threads Intel Software College.
Linux Programming –Threads CS Threads Review Threads in the same address space –share everything in the address space –lighter than process –no.
ECE 297 Concurrent Servers Process, fork & threads ECE 297.
Threads.
1 Threads Chapter 11 from the book: Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date:
CS333 Intro to Operating Systems Jonathan Walpole.
Pthreads: A shared memory programming model
Threads Chapter 26. Threads Light-weight processes Each process can have multiple threads of concurrent control. What’s wrong with processes? fork() is.
1 Pthread Programming CIS450 Winter 2003 Professor Jinhua Guo.
POSIX Synchronization Introduction to Operating Systems: Discussion Module 5.
POSIX Threads HUJI Spring 2011.
IT 325 Operating systems Chapter6.  Threads can greatly simplify writing elegant and efficient programs.  However, there are problems when multiple.
Pthreads.
Discussion Week 2 TA: Kyle Dewey. Overview Concurrency Process level Thread level MIPS - switch.s Project #1.
Pthreads #include pthread_t tid ; //thread id. pthread_attr_t attr ; void *sleeping(void *); /* thread routine */ main() { int time = 2 ; pthread_create(&tid,
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Software Systems Advanced Synchronization Emery Berger and Mark Corner University.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Unix System Calls and Posix Threads.
12/22/ Thread Model for Realizing Concurrency B. Ramamurthy.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Operating Systems Processes and Threads.
PThread Synchronization. Thread Mechanisms Birrell identifies four mechanisms commonly used in threading systems –Thread creation –Mutual exclusion (mutex)
Thread S04, Recitation, Section A Thread Memory Model Thread Interfaces (System Calls) Thread Safety (Pitfalls of Using Thread) Racing Semaphore.
Thread Basic Thread operations include thread creation, termination, synchronization, data management Threads in the same process share:  Process address.
POSIX THREADS. What is a thread? Multiple stands of execution in a single program are called threads. In other words, a thread is a sequence of control.
pThread synchronization
Case Study: Pthread Synchronization Dr. Yingwu Zhu.
Principles of Operating Systems Lecture 11
Threads Threads.
Netprog: Threads Programming
Thread Programming.
Chapter 4: Threads.
PTHREADS These notes are from LLNL Pthreads Tutorial
Multithreading Tutorial
Thread synchronization
Lecture 14: Pthreads Mutex and Condition Variables
Modified by H. Schulzrinne 02/15/10 Chapter 4: Threads.
Multithreading Tutorial
Thread Programming.
Unix System Calls and Posix Threads
Pthread Prof. Ikjun Yeom TA – Mugyo
Chien-Chung Shen CIS/UD
Multithreading Tutorial
Multithreading Tutorial
Lecture 14: Pthreads Mutex and Condition Variables
POSIX Threads(pthreads)
Presentation transcript:

Thread-Safe Programming Living With Linux

Thread-Safe Programming Tommy Reynolds Fedora Documentation Project Steering Committee

What Are Threads? Multiple execution paths in a single program. Threads share common address space, credentials, and resource limits. POSIX threading model assumes threads are not visible to the O/S kernel. Linux doesn’t work this way.

Native POSIX Thread Library Traditional POSIX threads require an application-side manager thread 1.O/S schedules application based on overall behavior 2.Application’s manager thread chooses appropriate thread to run. On Linux, threads are known to kernel This lets Linux scheduler make an optimal choice

Mindset Warping Plan for multi-threaded behavior from the beginning “Multi-threaded” is all or nothing; even one little thread brings ALL the thread synchronization problems to the forefront Always think “is it safe for my other application threads to run while I’m executing this statement” is appropriate paranoia

Compiling A Threaded Program Compiler dependent, no standard technique Often, special defines and libraries are needed Preferred GCC method: $ gcc -pthread -o foo foo.c

Application Considerations Threaded application is a different animal from traditional applications Any thread could start running at any time Resources shared between threads must be carefully guarded. Synchronization tools 1.Semaphore (aka MUTEX) 2.Condition Variables (aka CV)

Your First Thread Is Free... In every program, a default thread is created that runs the main() function Traditional POSIX implementations also create a manager thread, but Linux doesn't All other threads are created by application Unlike fork / wait model, there is no parent / child relationship among threads. Knowing when sibling thread terminates takes special effort.

Keeping The Balance Traditional applications can use fork(2) and wait(2) to manage processes. Threads use pthread_create(P) and pthread_join(P) to a similar purpose. Threads are expected to return an exit status. Threads may be detached if the exit status is of no interest; avoid zombie threads!

Shape Of A Thread #include void * thread( void *arg ) { myarg_t * myarg = arg; intresults;... pthread_exit( &results ); }

Cleaning Up Cleanly #include... void unwind( void * arg ) { /* Whatever */ } void * thread( void * arg ) { pthread_cleanup_push( unwind, arg ); /* Funky stuff */ pthread_cleanup_pop( 1 ); pthread_exit( NULL ); }

Signal Handling Threads all share signal handlers Asynchronous signals (SIGHUP, SIGTERM, SIGUSR1) offered to all threads in a process Synchronous signals (SIGFPE, SIGBUS, SIGSEGV) delivered to offending thread Use pthread_kill(P) to send signal to a specific thread

What Are Shared Resources? Global variables accessed (read or write) by multiple threads Shared data areas (read or write); often passed via pointer Most standard library routines – many have re-entrant versions Even malloc(3) and free(3) are not thread safe

Critical Regions Considered Harmful Puts guards around lines of code that access shared resources disable_interrupts() hw->reg &= ~(1 << 10) enable_interrupts() Wrong focus – protect shared resources, not code Think about shared resources, not code

Application Toolkit Needed for the same reason you can’t call printf() from a signal handler. Use semaphores (MUTEX) and Condition Variables Avoid race conditions, where the result depends on who finishes first Non-repeatable behavior is very hard to debug

Semaphores (Spelled “MUTEX”) POSIX version of Nicholas Wirth’s P/V semaphores (yes / no decisions) Defined in Always in either locked or unlocked state pthread_mutex_lock() blocks until lock is unlocked and then returns pthread_mutex_unlock() unlocks semaphore, awakens any blocked threads

Example Using MUTEX #include pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; static int k; void * producer( void * arg ) { pthread_mutex_lock( &m ); ++k; pthread_mutex_unlock( &m ); } void * consumer( void * arg ) { pthread_mutex_lock( &m ); printf( “k = %d\n”, k ); pthread_mutex_unlock( &m ); }

Condition Variables Semaphores are for yes or no decisions Condition Variables permit complicated decisions to be made atomically Guards the test (function call!) with a MUTEX Grabs the MUTEX; checks the condition; if not true, release MUTEX then block then re-acquire MUTEX without missing anything

Condition Variable Example #include pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cv = PTHREAD_COND_INITIALIZER; void * consumer( void * ) { pthread_mutex_lock( &m ); while( check_for_messages() == 0 ) { pthread_cond_wait( &cv, &m ); } consume_messages(); pthread_mutex_unlock( &m ); } void * producer( void * ) { pthread_mutex_lock( &m ); accept_another_message(); pthread_cond_broadcast( &cv ); pthread_mutex_unlock( &m ); }

Using Standard Library With Threads Thread-safe standard library version of foo() is usally named foo_r() Protect others using a MUTEX pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; … pthread_mutex_lock( &m ); ptr = malloc( 10 ); pthread_mutex_unlock( &m ); …

Accessing One File From Two Threads Use O_EXCL for open(2) system call, although this is advisory only Threads within the same process can wrap the access with a MUTEX Separate applications often link(2) a known filename, do the access, then unlink(2) the guard file

In Summary, En Passant POSIX-standard thread API permits portable programs with expected behavior Requires “three-dimensional” thinking by the application programmer Seemingly innocuous practices can be fraught with peril – programmers must be aware of ALL threats There is no cook-book solution

Protect Your Thread Territory -or- This Is The End