6.824 Lecture 2: Threads and RPC How many of you have experience with programming with threads? Thread is short for thread of control, a running program with its own program counter, stack pointer, etc. (For this class a process is a one of more threads executing in a single address space.) Primary purpose: a way of running code concurrently within a single process. For example, in lab 1, if one client is waiting for lock a, the server may want to process requests from other clients, in particular ones for different locks. The primary reasons to use concurrent programming with threads: exploit several processors to run an application faster hide long delays (e.g., while waiting for a disk do something else on processor) run long-running ops concurrenty with short ones in user interfaces network servers and RPC At a minimum, a thread interface must support: creating and managing threads ways of avoiding race conditions for updates to shared variables assume each treads runs on its own processor, sharing a memory instructions that appear to be atomic, might not be (e.g., x = x + 1) ways of coordinating different threads Pthread interface standard interface, not unlike the one described in the paper, but programming language independent. we use it in the labs Interface threads create join mutex lock can the same thread acquire the lock again? avoid recursive locks unlock (must typically be performed by the thread that did the acquire) condition variables wait signal wakes up one thread is it the right one? only use it if there is only one thread waiting broadcast wakes up all threads waiting put waiting condition in a loop around wait if only one should proceed e.g., if multiple clients are waiting on a lock from the lock server Pitfall of multithreaded programming race condition; can you give me an example? may be difficult to reproduce deadlock; can you give me an example? better bug to have than race; you program stops when it happens wrong lock granularity; can you give me an example? starvation; can you give me an example? Multithreaded programming is more difficult than sequential programming! worth to reread the paper as you get more experience How to use the interface. Let's look at lock_tester.cc: count_mutex note that it must be initialized with pthread_mutex_init. why do check_grant and check_release use it? main how are threads created? how can you wait on a thread termination? what is the differences between test3, test4, and test5? Lab 1 How do you make an RPC call see lock_demo.cc What is the call semantics? request may arrive 0, 1, 2, ... times at the server RPC semantics impact on lab1? duplicates may arrive More next lecture when looking at the implementation of the RPC library.