[\<- Notes 02/14](02-14.md) --- # Recursion Continued - Recursion - Tiny Code - No Loops - Condition to Stop (otherwise it will go forever) - For more, see page 353-355 in textbook --- # Multi-Threading ## Process - A process, in the simplest terms, is an executing program - A process can contain multiple threads ## Threads - Threads are lightweight processes - Each process can execute several threads - The threads execute **independently** - Threads **share** the global variables and OS resources - Each thread has its **own stack** and follow its **own execution flow** - In practice - Main program creates threads - By specifying an entry point function and an argument - The main program and each created thread run independently - They share global variables - They do not share local variables - Example of functions to handle threads - Creation - Exit - Cancellation - Synchronization - Example: - Alternating Threads - Creates 3 threads - Let the system execute them in a round-robin fashion - Wait for them to finish at main ``` int main(){ int i; for(i = 0; i < 3; i++){ //create thread to execute function loop() with parameter i } //wait for each thread to finish } void loop(int n){ int i; for(i = 0; i < 20; i++){ printf("Thread %d\n", n); sleep(1); } } ``` - Need synchronization - Solution: - Lock - Conditional Variables - Semaphores --- [-> Notes 02/26](02-26.md)