2018-01-24

[筆記] Socket programing I/O Model 類比介紹

### Blocking I/O Model:

User application requests Kernel for UDP datagram by using recvfrom.

The UDP datagram to user application just has two status: ready or not ready.

PS. system call這邊是採用recvfrom



1. System call

小明(User application)拿著他的盤子(Uesr application buffer),

請求(system call) 煎檯的廚師(Kernel) 給他牛肉(datagram)。



2. Application is blocking

由於餐廳規定小明跟廚師要牛肉必須要在煎檯前面等不能走開 (the file descriptor is blocking),

因此小明(User application)只能等待廚師回應(return status),不能走開(blocking)



3. Wait for data

而廚師(Kernel)的煎檯(Kernel buffer)尚未放置牛肉(no datagram ready),

因此需要等待上游廠商牛肉送過來(wait for data)



4. Copy datagram

當上游廠商牛肉到達(data arrival)至廚師(Kernel)的煎檯(Kernel buffer),

因此煎檯(Kernel buffer)上的牛肉已經準備好了(datagram ready)



5. Copy data from kernel to user

過一會廚師(Kernel)再把牛肉(datagram)放置(copy datagram)給小明的盤子(Uesr application buffer)。



6. Copy complete

放置完成(copy complete)之後,廚師(Kernel)就會跟小明(User application)說OK (return status is OK)

,小明可以不用等了。



7. Process datagram

爾後小明就可以從煎檯離開,開始享用牛肉(Process datagram)





###  Non-Blocking  I/O Model

1. System call

小明(User application)拿著他的盤子(Uesr application buffer),

請求(system call) 煎檯的廚師(Kernel) 給他牛肉(datagram)。



2. Application is non-blocking

由於餐廳規定小明可以不用在煎台等(the file descriptor is non-blocking),

因此小明(User application) 可以先離開煎檯,隔一段時間再回來,可不斷詢問(polling)可以問廚師說牛排(datagram ready)好了沒?

這時候會有兩種case:

a. 廚師(Kernel)的煎檯(Kernel buffer)尚未放置牛肉(no datagram ready),
廚師回應(return status) 還沒,小明可以走開,晚點再詢問。

b. 廚師(Kernel)的煎檯(Kernel buffer)已放置牛肉(datagram ready),
廚師回應(return status) 好了,廚師(Kernel)再把牛肉(datagram)放置(copy datagram)給小明的盤子(Uesr application buffer),
小明可以走開。


## 同步跟非同步
這兩者差別不在於小明詢問廚師牛排好了沒,也就是不管前面是否會被阻塞(blocking)的動作。

而是以下這個動作:

廚師(Kernel)再把牛肉(datagram)放置(copy datagram)給小明的盤子(Uesr application buffer),

- 同步的話就是,廚師(Kernel)把小明(User application)叫住(blocking),還是要把牛肉(datagram)放置(copy datagram)給小明的盤子(Uesr application buffer),
小明才可以走開。

- 非同步,也就是異步,廚師可以偷偷在小明不知情的情況下把牛肉放置到小明的盤子上,然後才告訴小明說你的牛肉好了,
小明可以直接享用,在這過程中小明完全不會被廚師攔下來。

也就是說小明可能在拿著盤子在走路,廚師像忍者一樣,不急不徐地偷偷把肉放在小明盤子,放完之後跟小明講你牛肉好了。

# 結論
阻塞跟不阻塞,談的是user application 請求 kernel 的資料方式,要嘛問完就等著(blocking);要嘛問完就離開(non-blocking)。
同步跟非同步,談的是kernel 要用什麼方式把資料放在user application的盤子上。要嘛廚師把你抓住慢慢放完肉在你盤子上才讓你走(同步),要嘛在你邊走路情況下,直接把肉偷偷放在你盤子上(非同步)


沒有留言: