diff options
author | loshprung <lshprung@scu.edu> | 2020-02-24 11:32:29 -0800 |
---|---|---|
committer | loshprung <lshprung@scu.edu> | 2020-02-24 11:32:29 -0800 |
commit | ca14d94afff3af31bd2844f605aa20d851bc7f31 (patch) | |
tree | 92cedfaa604b2debb522b5637d5b2ccc67bc8bef /02-21.md | |
parent | c25938a3064b1cc73af26ea8db297a55f26949bf (diff) |
Post-class 02/24
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 |