Concurrency I: Threads Nov 9, 2000Topics• Thread concept• Posix threads (Pthreads) interface• Linux Pthreads implementation• Concurrent execution• Sharing dataclass22.ppt15-213“The course that gives CMU its Zip!”CS 213 F’00– 2 –class22.pptTraditional view of a processshared librariesrun-time heap0read/write dataProcess = process context + code, data, and stackProgram context: Data registers Condition codes Stack pointer (SP) Program counter (PC)Kernel context: VM structures Open files Signal handlers brk pointerCode, data, and stackread-only code/datastackSPPCbrkProcess contextCS 213 F’00– 3 –class22.pptModern view of a processshared librariesrun-time heap0read/write dataProcess = thread + code, data, and kernel contextThread context: Data registers Condition codes Stack pointer (SP) Program counter (PC) Code and Dataread-only code/datastackSPPCbrkThread (main thread)Kernel context: VM structures Open files Signal handlers brk pointerCS 213 F’00– 4 –class22.pptA process with multiple threadsshared 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 Open files Signal handlers brk pointerMultiple 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)Thread 2 context: Data registers Condition codes SP2 PC2stack 2Thread 2 (peer thread)CS 213 F’00– 5 –class22.pptLogical view of threadsThreads associated with a process form a pool of peers.• unlike processes which form a tree hierarchyP0P1sh sh shfoobarT1Process hierarchyThreads associated with process fooT2T4T5T3shared code, dataand kernel contextCS 213 F’00– 6 –class22.pptConcurrent thread executionTwo threads run concurrently (are concurrent) if theirlogical flows overlap in time.Otherwise, they are sequential.Examples:• Concurrent: A & B, A&C• Sequential: B & CTimeThread A Thread B Thread CCS 213 F’00– 7 –class22.pptThreads vs processesHow threads and processes are similar• Each has its own logical control flow.• Each can run concurrently.• Each is context switched.How threads and processes are different• Threads share code and data, processes (typically) do not.• Threads are somewhat less expensive than processes.–process control (creating and reaping) is twice as expensive as threadcontrol.–Linux/Pentium III numbers:»20K cycles to create and reap a process.»10K cycles to create and reap a thread.CS 213 F’00– 8 –class22.pptThreads are a unifying abstraction for exceptional control flowException handler• A handler can be viewed as a thread• Waits for a "signal" from CPU• Upon receipt, executes some code, then waits for next "signal"Process• A process is a thread + shared code, data, and kernel context.Signal handler• A signal handler can be viewed as a thread• Waits for a signal from the kernel or another process• Upon receipt, executes some code, then waits for next signal.CS 213 F’00– 9 –class22.pptPosix threads (Pthreads) interfacePthreads: Standard interface for ~60 functions thatmanipulate 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] , ret [terminates current thread]• Synchronizing access to shared variables–pthread_mutex_init–pthread_mutex_[un]lock–pthread_cond_init–pthread_cond_[timed]waitCS 213 F’00– 10 –class22.pptThe Pthreads "hello, world" program/* * hello.c - Pthreads "hello, world" program */#include <ics.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) return value(void **p)CS 213 F’00– 11 –class22.pptExecution of “hello, world”main thread peer threadcreate peer threadprint outputterminate thread via retwait for peer thread to terminateexit() terminates main thread and anypeer threadsCS 213 F’00– 12 –class22.pptUnix vs Posix error handlingUnix-style error handling (Unix syscalls)• if error: return -1 and set errno variable to error code.• if OK: return useful result as value >= 0.Posix-style error handling (newer Posix functions)• if error: return nonzero error code, zero if OK• useful results are passed back in an argument.if ((pid = wait(NULL)) < 0) { perror("wait"); exit(0);}if ((rc = pthread_join(tid, &retvalp)) != 0) { printf(”pthread_create: %s\n", strerror(rc)); exit(0);}CS 213 F’00– 13 –class22.pptSuggested error handling macrosError checking crucial, but cluttered. Use these tosimplify your error checking:/* * macro for posix-style error handling */#define posix_error(code,msg) do {\ printf("%s: %s\n", msg, strerror(code));\ exit(0);\} while (0)/* * macro for unix-style error handling */#define unix_error(msg) do {\ printf("%s: %s\n", msg, strerror(errno));\ exit(0);\} while (0)CS 213 F’00– 14 –class22.pptPthreads wrappersWe advocate Steven’s convention of providingwrappers for each system-level function call.• wrapper is denoted by capitalizing first letter of function name.• wrapper has identical interface as the original function.• each wrapper does appropriate unix or posix style error checking.• wrapper typically return nothing.• declutters code without compromising safety./* * wrapper function for pthread_join */void Pthread_join(pthread_t tid, void **thread_return) { int rc = pthread_join(tid, thread_return); if (rc != 0) posix_error(rc, "Pthread_join");}CS 213 F’00– 15 –class22.pptBasic thread control: create a threadCreates a new peer thread• tidp: thread id• attrp: thread attributes (usually NULL)• routine: thread routine• argp: input parameters to routineAkin to fork()• but without the confusing “call once return twice” semantics.• peer thread has local stack variables, but shares all global variables.int pthread_create(pthread_t *tidp, pthread_attr_t *attrp, void *(*routine)(void *), void *argp);CS 213 F’00–
View Full Document