April 10th Lecture ===================== Recall from earlier: int x = 0; int main(void) { fork(); x++; printf("x = %d\n", x); } Output: x = 1 x = 1 We get the same output from each forked process since each process gets a separate copy of the program's memory, a personal copy of x * Good model for webservers, database servers, etc., where multiple identical handlers are needed to process separate, independent requests. * Suppose we didn't want separate copies of the data, but would rather share variable values between two chains of execution inside the program...this model is accomplished through the use of threads. thread - a unit of execution of a process - separate CPU registers - separate stack - *shared* address space Example use: web browser * UI thread * HTML parsing/validating thread * network handling thread All can communicate via shared memory and global variables Every process has at least 1 thread when it starts up. concurrent program - a program that creates >1 process or thread advantages of concurrent programs: + separate interactive parts of the program from CPU-bound parts (i.e. performance) + maybe: more logical, simple design for multiple subtasks + takes advantage of >1 CPU advantages of threads over processes: + save memory + simplify communication (i.e., shared message rather than explicit message passing) + performance: faster to spawn lots of threads than lots of processes Threads - Shared: code (text segment), static data (globals), open files, signals/signal handlers (only one thread responds) - Separate: CPU register state, running state (RUN, READY, WAITING) 2 types of threads: user & kernel - user threads: * implemented by a library "mini-os" that is linked into the compiled program * kernel is only aware of one proc, oblivious to threads - kernel threads: * kernel provides system calls for creating and managing threads User level threads: + *fast* context switches (no need to enter kernel mode) - single processor support only - I/O in any thread may block entire process if not careful - not scheduled "fairly" with respect to other kernel-level procs/threads * usually cooperative scheduling rather than preemptive thread interface -- a well-defined set of functions that will be provided for managing threads; may be implemented many different ways behind the scenes; ex: pthreads is an interface...there are several different implementations most Unix-like operating systems use pthreads as the threading *interface* but implement threads very differently * FreeBSD: kthread_create() system call * Linux: clone() system call