summaryrefslogtreecommitdiff
path: root/02-21.md
blob: 045fdffcce206930a565a6133526acbb7ad586e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
[\<- 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)