Slide 1Don’t Miss Your Chance …..TodayProcess: Traditional ViewProcess: Alternative ViewProcess with Two ThreadsThreads vs. ProcessesThreads vs. Processes (contd.)Posix Threads (Pthreads) InterfaceThe Pthreads “Hello, world" ProgramDetaching ThreadsPros and Cons of Thread-Based DesignsTodayShared Variables in Threaded C ProgramsThreads Memory ModelThread Accessing Another Thread’s StackMapping Variables to Memory InstancesShared Variable Analysisbadcnt.c: Improper SynchronizationAssembly Code for Counter LoopConcurrent ExecutionConcurrent Execution (cont)Concurrent Execution (cont)Progress GraphsTrajectories in Progress GraphsCritical Sections and Unsafe RegionsCritical Sections and Unsafe RegionsSemaphoresbadcnt.c: Improper SynchronizationSafe Sharing with SemaphoresSafe Sharing With SemaphoresWrappers on POSIX SemaphoresSharing With POSIX SemaphoresTodayOne worry: racesRace EliminationAnother worry: DeadlockDeadlocking With POSIX SemaphoresDeadlock Visualized in Progress GraphAvoiding DeadlockAvoided Deadlock in Progress GraphCrucial concept: Thread SafetyThread-Unsafe Functions (Class 1)Thread-Unsafe Functions (Class 2)Making Thread-Safe RNGThread-Unsafe Functions (Class 3)Thread-Unsafe Functions (Class 4)Thread-Safe Library FunctionsNotifying With SemaphoresProducer-Consumer on a Buffer That Holds One ItemProducer-Consumer (cont)Counting with SemaphoresCounting with semaphores (cont)Threads SummaryCarnegie MellonIntroduction to Computer Systems15-213/18-243, spring 200926th Lecture, Apr. 28thInstructors: Gregory Kesden and Markus PüschelCarnegie MellonDon’t Miss Your Chance …..A, B, ….meCarnegie MellonTodayThreads: basicsSynchronizationRaces, deadlocks, thread safetyCarnegie MellonProcess: Traditional ViewProcess = process context + code, data, and stackshared librariesrun-time heap0read/write dataProgram context: Data registers Condition codes Stack pointer (SP) Program counter (PC)Code, data, and stackread-only code/datastackSPPCbrkProcess contextKernel context: VM structures Descriptor table brk pointerCarnegie MellonProcess: Alternative ViewProcess = thread + code, data, and kernel contextshared librariesrun-time heap0read/write dataProgram context: Data registers Condition codes Stack pointer (SP) Program counter (PC)Code, data, and kernel contextread-only code/datastackSPPCbrkThreadKernel context: VM structures Descriptor table brk pointerCarnegie MellonProcess with Two Threadsshared librariesrun-time heap0read/write dataProgram context: Data registers Condition codes Stack pointer (SP) Program counter (PC)Code, data, and kernel contextread-only code/datastackSPPCbrkThread 1Kernel context: VM structures Descriptor table brk pointerProgram context: Data registers Condition codes Stack pointer (SP) Program counter (PC)stackSPThread 2Carnegie MellonThreads vs. ProcessesThreads and processes: similaritiesEach has its own logical control flowEach can run concurrently with othersEach is context switched (scheduled) by the kernelThreads and processes: differencesThreads share code and data, processes (typically) do notThreads are much less expensive than processesProcess control (creating and reaping) is more expensive as thread controlContext switches for processes much more expensive than for threadsCarnegie MellonThreads vs. Processes (contd.)Processes form a tree hierarchyThreads form a pool of peersEach thread can kill any otherEach thread can wait for any other thread to terminateMain thread: first thread to run in a processP0P1sh sh shfooT1Process hierarchyThread poolT2T4T5T3shared code, dataand kernel contextCarnegie MellonPosix Threads (Pthreads) InterfacePthreads: Standard interface for ~60 functions that manipulate threads from C programsThreads run thread routines:void *threadroutine(void *vargp)Creating and reaping threadspthread_create(pthread_t *tid, …, func *f, void *arg)pthread_join(pthread_t tid, void **thread_return)Determining your thread IDpthread_self()Terminating threadspthread_cancel(pthread_t tid)pthread_exit(void *tread_return)return (in primary thread routine terminates the thread)exit() (terminates all threads) Synchronizing access to shared variablesCarnegie MellonThe Pthreads “Hello, world" Program/* * hello.c - Pthreads "hello, world" program */#include "csapp.h"void *thread(void *vargp);int main() { pthread_t tid; Pthread_create(&tid, NULL, thread, NULL); Pthread_join(tid, NULL); exit(0);}/* thread routine */void *thread(void *vargp) { printf("Hello, world!\n"); return NULL;}Thread attributes (usually NULL)Thread arguments(void *p) assigns return value(void **p)Carnegie MellonDetaching ThreadsThread-based servers: Use “detached” threads to avoid memory leaksAt any point in time, a thread is either joinable or detachedJoinable thread can be reaped and killed by other threadsmust be reaped (with pthread_join) to free memory resourcesDetached thread cannot be reaped or killed by other threadsresources are automatically reaped on terminationDefault state is joinableuse pthread_detach(pthread_self()) to make detachedMust be careful to avoid unintended sharingFor example, what happens if we pass the address of connfd to the thread routine?Pthread_create(&tid, NULL, thread, (void *)&connfd);Carnegie MellonPros and Cons of Thread-Based Designs+ 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!The ease with which data can be shared is both the greatest strength and the greatest weakness of threadsCarnegie MellonTodayThreads: basicsSynchronizationRaces, deadlocks, thread safetyCarnegie MellonShared Variables in Threaded C ProgramsQuestion: Which variables in a threaded C program are shared variables?The answer is 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 each memory instance?How many threads might reference each of these instances?Carnegie MellonThreads Memory ModelConceptual model:Multiple threads run within the context of a single processEach thread has its own separate
View Full Document