8. Terminology
• Blocking I/O
• Non-Blocking I/O
• Synchronous
• Asynchronous
Can you tell me what’s the difference?
8
9. Before the explanation
In unix world, we need to consider about
User space(thread or process) & Kernel space
e.g when we invoke a read operator
1. Waiting for data to be ready
2. Copying the data from kernel to the process
9
14. Answer
Blocking IO & Non-Blocking IO are determined by function call
1. A synchronous I/O operation causes the requesting process to
be blocked until that I/O operation completes;
2. An asynchronous I/O operation does not cause the requesting
process to be blocked;
14
19. Asynchronous Model
Single Thread
Multi Thread
19
T1 T2 T1
Thread
T3 T2 T3
T2 T1
Thread1
T1 T3T1 T3
T6 T5
Thread2
T4 T2T4 T5
T10 T11
Thread3
T11 T9T9 T10
20. 4 Scenarios
1. Synchronous Single Thread
2. Synchronous Multi Thread
3. Asynchronous Single Thread
4. Asynchronous Multi Thread
20
21. Concurrency
In simple terms, concurrency means processing multiple requests
at a time.
e.g chef can finish multiple tasks at a time.
- chopping
- prepare sauces
- cooking main dishes
...
21
26. Event loop
Port binding, add
FD to watch list
FD0 FD1 FD2 FD3
Select watch list
Wait for activity
in the watch list
by using Select
Client connects,
add to watch list
Check all FD for
available data
Client disconnects,
remove from watch list
Execute handler to
deal with fd
https://blog.logentries.com/2016/07/what-exactly-is-an-event-loop/
27. Event loop
1. Take advantage of IO multiplexing
a. select O(n)
b. epoll O(1)
2. Eliminate idle time
27
38. Coroutine
Couroutine are computer program components
that generalize subroutines to allow multiple entry points
for suspending and resuming execution at
certain locations
https://en.wikipedia.org/wiki/Coroutine
39. Coroutine
function *test() {
console.log(‘there’);
var x = yield;
console.log(‘hi’ + x);
var y = yield;
console.log(‘hi + y);
}
var tester = test()
tester.next() // there
tester.next(‘joe’) // hi joe
tester.next(‘daniel’) // hi daniel
Main Coroutine1
yield
yield
spawn
switch
40. Coroutine
function *request() {
var resp = yield* getUrlAsync(‘www.umbocv.com’)
return resp
}
var resp_json = request().next().value
When you run asynchronous function,
Use yield pass control to other coroutine
42. async/await
async function getUrlAsync() {
....
}
async function request() {
const resp = await getUrlAsync(‘www.umbocv.com’)
return resp
}
var resp_json = request()
Use await to invoke asynchronous function and pass control to
another function.
44. Homework
1. Figure out what’s the benefit of using select & epoll (e.g c10 problem)
2. Libuv (nodejs, gevent)
3. What is green thread and what’s the relationship with coroutine