Programming with ThreadsTraditional View of a ProcessAlternate View of a ProcessA Process With Multiple ThreadsLogical View of ThreadsConcurrent Thread ExecutionThreads vs. ProcessesPosix Threads (Pthreads) InterfaceThe Pthreads "hello, world" ProgramExecution of Threaded “hello, world”Pros and Cons of Thread-Based DesignsShared Variables in Threaded C ProgramsThreads Memory ModelExample of Threads Accessing Another Thread’s StackMapping Vars to Mem. InstancesShared Variable Analysisbadcnt.c: An Improperly Synchronized Threaded ProgramAssembly Code for Counter LoopConcurrent ExecutionWhat is “Sequential Consistency?”Concurrent Execution (cont.)Concurrent Execution (cont)Progress GraphsTrajectories in Progress GraphsCritical Sections and Unsafe RegionsSafe and Unsafe TrajectoriesRacesSemaphoresSafe Sharing with SemaphoresSafe Sharing With SemaphoresDeadlockPOSIX SemaphoresSharing With POSIX SemaphoresSignaling With SemaphoresProducer-Consumer on Buffer That Holds One ItemProducer-Consumer (cont)Thread SafetyThread-Unsafe FunctionsThread-Unsafe Functions (cont)Slide 40Slide 41Reentrant FunctionsThread-Safe Library FunctionsThreads SummaryProgramming with ThreadsTopicsThreadsShared variablesThe need for synchronizationSynchronizing with semaphoresThread safety and reentrancyRaces and deadlocksCS 105“Tour of the Black Holes of Computing!”– 2 –CS 105Traditional View of a ProcessProcess = process context + code, data, and stackshared librariesrun-time heap0read/write dataProgram context: Data registers Condition codes Stack pointer (SP) Program counter (PC)Kernel context: VM structures File descriptor table brk pointerCode, data, and stackread-only code/datastackSPPCbrkProcess context– 3 –CS 105Alternate View of a ProcessProcess = thread + code, data, and kernel contextshared librariesrun-time heap0read/write dataThread context: Data registers Condition codes Stack pointer (SP) Program counter (PC) Code and Dataread-only code/datastackSPPCbrkThread (main thread)Kernel context: VM structures File descriptor table brk pointer– 4 –CS 105A Process With Multiple ThreadsMultiple threads can be associated with a processEach thread has its own logical control flow (sequence of PC values)Each thread shares the same code, data, and kernel contextEach thread has its own thread id (TID)shared librariesrun-time heap0read/write dataThread 1 context: Data registers Condition codes SP1 PC1 Shared code and dataread-only code/datastack 1Thread 1 (main thread)Kernel context: VM structures File descriptor table brk pointerThread 2 context: Data registers Condition codes SP2 PC2stack 2Thread 2 (peer thread)– 5 –CS 105Logical View of ThreadsThreads associated with a process form pool of peersUnlike processes, which form tree hierarchyP0P1sh sh shfoobarT1Process hierarchyThreads associated with process fooT2T4T5T3shared code, dataand kernel context– 6 –CS 105Concurrent Thread ExecutionTwo threads run concurrently (are concurrent) if their logical flows overlap in timeOtherwise, they are sequential (same rule as for processes)Examples:Concurrent: A & B, A&CSequential: B & CTimeThread A Thread B Thread C– 7 –CS 105Threads vs. ProcessesHow threads and processes are similarEach has its own logical control flowEach can run concurrentlyEach is context switchedHow threads and processes are differentThreads share code and data, processes (typically) do notThreads are somewhat cheaper than processesProcess control (creating and reaping) is twice as expensive as thread control Linux/Pentium III numbers:»~20K cycles to create and reap a process»~10K cycles to create and reap a thread– 8 –CS 105Posix Threads (Pthreads) InterfacePthreads: Standard interface for ~60 functions that manipulate threads from C programsCreating and reaping threadspthread_create, pthread_joinDetermining your thread IDpthread_selfTerminating threadspthread_cancel, pthread_exitexit [terminates all threads] , return [terminates current thread]Synchronizing access to shared variablespthread_mutex_init, pthread_mutex_[un]lockpthread_cond_init, pthread_cond_[timed]wait– 9 –CS 105The Pthreads "hello, world" Program/* * hello.c - Pthreads "hello, world" program */#include "csapp.h"void *howdy(void *vargp);int main() { pthread_t tid; Pthread_create(&tid, NULL, howdy, NULL); Pthread_join(tid, NULL); exit(0);}/* thread routine */void *howdy(void *vargp) { printf("Hello, world!\n"); return NULL;}Thread attributes (usually NULL)Thread arguments(void *p) return value(void **p)– 10 –CS 105Execution of Threaded “hello, world”main threadpeer threadreturn NULL;main thread waits for peer thread to terminateexit() terminates main thread and any peer threadscall Pthread_create()call Pthread_join()Pthread_join() returnsprintf()(peer threadterminates)Pthread_create() returns– 11 –CS 105Pros and Consof Thread-Based Designs+ Threads take advantage of multicore/multi-CPU H/W+ Easy to share data structures between threadsE.g., logging information, file cache+ Threads are more efficient than processes– Unintentional sharing can introduce subtle and hard-to-reproduce errors!Ease of data sharing is greatest strength of threadsAlso greatest weakness!– 12 –CS 105Shared Variables in Threaded C ProgramsQuestion: Which variables in a threaded C program are shared variables?Answer not as simple as “global variables are shared” and “stack variables are private”Requires answers to the following questions:What is the memory model for threads?How are variables mapped to memory instances?How many threads reference each of these instances?– 13 –CS 105Threads Memory ModelConceptual model:Each thread runs in larger context of a processEach thread has its own separate thread contextThread ID, stack, stack pointer, program counter, condition codes, and general purpose registersAll threads share remaining process contextCode, data, heap, and shared library segments of process virtual address spaceOpen files and installed handlersOperationally, this model is not strictly enforced:Register values are truly separate and protectedBut any thread can read and write the stack of any other thread Mismatch between conceptual and operational model is a source of confusion and errors– 14 –CS 105Example of Threads
View Full Document