Carnegie MellonIntroduction to Computer Systems15-213, fall 200926thLecture, Nov. 25thInstructors:Majd Sakr and Khaled HarrasCarnegie MellonTodayThreads: basicsSynchronizationRaces, deadlocks, thread safetyCarnegie MellonProcess: Traditional ViewProcess = process context + code, data, and stackshared librariesrun-time heap0read/write dataProgram context:Data registersCondition codesStack pointer (SP)Program counter (PC)Code, data, and stackread-only code/datastackSPPCbrkProcess contextKernel context:VM structuresDescriptor tablebrk pointerCarnegie MellonProcess: Alternative ViewProcess = thread + code, data, and kernel contextshared librariesrun-time heap0read/write dataProgram context:Data registersCondition codesStack pointer (SP)Program counter (PC)Code, data, and kernel contextread-only code/datastackSPPCbrkThreadKernel context:VM structuresDescriptor tablebrk pointerCarnegie MellonProcess with Two Threadsshared librariesrun-time heap0read/write dataProgram context:Data registersCondition codesStack pointer (SP)Program counter (PC)Code, data, and kernel contextread-only code/datastackSPPCbrkThread 1Kernel context:VM structuresDescriptor tablebrk pointerProgram context:Data registersCondition codesStack 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 threads pthread_create(pthread_t *tid, …, func *f, void *arg) pthread_join(pthread_t tid, void **thread_return)Determining your thread ID pthread_self()Terminating threads pthread_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 thread context Thread ID, stack, stack pointer, program counter, condition codes, and general purpose registersAll threads share the remaining process context Code, data, heap, and shared library segments of the process virtual address space Open files and installed handlersOperationally, this model is not strictly enforced:Register values are truly separate and protected, butAny thread can read and write the stack of any other threadMismatch between the conceptual and operation model is a source of confusion and errorsCarnegie MellonThread Accessing Another Thread’s Stackchar **ptr; /* global */int main(){int i;pthread_t tid;char *msgs[2] = {"Hello from foo","Hello from bar"};ptr = msgs;for (i = 0; i < 2; i++)Pthread_create(&tid, NULL, thread, (void *)i);Pthread_exit(NULL);}/* thread routine */void *thread(void *vargp){int myid = (int) vargp;static int svar = 0;printf("[%d]: %s (svar=%d)\n", myid, ptr[myid], ++svar);}Peer threads access main thread’s stackindirectly through global ptr variableCarnegie MellonMapping Variables to Memory Instanceschar **ptr; /* global */int main(){int i;pthread_t tid;char *msgs[2] = {"Hello from foo","Hello from bar"};ptr = msgs;for (i = 0; i < 2; i++)Pthread_create(&tid, NULL, thread, (void *)i);Pthread_exit(NULL);}/* thread routine */void *thread(void *vargp){int myid = (int)vargp;static int svar = 0;printf("[%d]: %s (svar=%d)\n", myid, ptr[myid], ++svar);}Global var: 1 instance (ptr [data])Local static var: 1 instance (svar[data])Local vars: 1 instance (i.m, msgs.m)Local var: 2 instances (myid.p0 [peer thread 0’s
View Full Document