Harvey Mudd CS 105 - Programming with Threads

Unformatted text preview:

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 ThreadsTopicsThreadsShared variablesThe need for synchronizationSynchronizing with semaphoresThread safety and reentrancyRaces 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 processEach thread has its own logical control flow (sequence of PC values)Each thread shares the same code, data, and kernel contextEach 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 peersUnlike 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&CSequential: B & CTimeThread A Thread B Thread C– 7 –CS 105Threads vs. ProcessesHow threads and processes are similarEach has its own logical control flowEach can run concurrentlyEach is context switchedHow threads and processes are differentThreads share code and data, processes (typically) do notThreads are somewhat cheaper than processesProcess 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 programsCreating and reaping threadspthread_create, pthread_joinDetermining your thread IDpthread_selfTerminating threadspthread_cancel, pthread_exitexit [terminates all threads] , return [terminates current thread]Synchronizing access to shared variablespthread_mutex_init, pthread_mutex_[un]lockpthread_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 threadsE.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 threadsAlso 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 processEach thread has its own separate thread contextThread ID, stack, stack pointer, program counter, condition codes, and general purpose registersAll threads share remaining process contextCode, data, heap, and shared library segments of process virtual address spaceOpen files and installed handlersOperationally, this model is not strictly enforced:Register values are truly separate and protectedBut 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

Harvey Mudd CS 105 - Programming with Threads

Documents in this Course
Processes

Processes

25 pages

Processes

Processes

27 pages

Load more
Download Programming with Threads
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Programming with Threads and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Programming with Threads 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?