Carnegie MellonIntroduction to Computer Systems15-213/18-243, spring 200926thLecture, Apr. 28thInstructors:Gregory Kesden and Markus PüschelCarnegie MellonToday Threads: basics Synchronization Races, deadlocks, thread safetyCarnegie MellonProcess: Traditional View Process = 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 View Process = 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. Processes Threads and processes: similarities Each has its own logical control flow Each can run concurrently with others Each is context switched (scheduled) by the kernel Threads and processes: differences Threads share code and data, processes (typically) do not Threads are much less expensive than processes Process control (creating and reaping) is more expensive as thread control Context switches for processes much more expensive than for threadsCarnegie MellonThreads vs. Processes (contd.) Processes form a tree hierarchy Threads form a pool of peers Each thread can kill any other Each thread can wait for any other thread to terminate Main thread: first thread to run in a processP0P1sh sh shfooT1Process hierarchyThread poolT2T4T5T3shared code, dataand kernel contextCarnegie MellonPosix Threads (Pthreads) Interface Pthreads: Standard interface for ~60 functions that manipulate threads from C programs Threads 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 Threads Thread-based servers: Use “detached” threads to avoid memory leaks At any point in time, a thread is either joinable or detached Joinable thread can be reaped and killed by other threads must be reaped (with pthread_join) to free memory resources Detached thread cannot be reaped or killed by other threads resources are automatically reaped on termination Default state is joinable use pthread_detach(pthread_self()) to make detached Must be careful to avoid unintended sharing For 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 threads e.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 MellonToday Threads: basics Synchronization Races, deadlocks, thread safetyCarnegie MellonShared Variables in Threaded C Programs Question: 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 Model Conceptual model: Multiple threads run within the context of a single 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 the remaining process context Code, data, heap, and shared library segments of the process virtual address space Open files and installed handlers Operationally, 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 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
View Full Document