diff options
Diffstat (limited to '02-21.md')
-rw-r--r-- | 02-21.md | 74 |
1 files changed, 74 insertions, 0 deletions
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 |