From ca14d94afff3af31bd2844f605aa20d851bc7f31 Mon Sep 17 00:00:00 2001 From: loshprung Date: Mon, 24 Feb 2020 11:32:29 -0800 Subject: Post-class 02/24 --- 02-14.md | 4 ++++ 02-21.md | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 02-21.md diff --git a/02-14.md b/02-14.md index fd184de..348dcde 100644 --- a/02-14.md +++ b/02-14.md @@ -118,3 +118,7 @@ int fibonacci(int n){ return ans; } ``` + +--- + +[-> Notes 02/21](02-21.md) diff --git a/02-21.md b/02-21.md new file mode 100644 index 0000000..52cccc2 --- /dev/null +++ b/02-21.md @@ -0,0 +1,74 @@ +[\<- 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 -- cgit