阻塞式IO是帶限速的。比如nc從/dev/zero讀取數據,然後寫到某個socket,如果接收socket速度慢,那麼從/dev/zero讀取也會慢
thread per connection 適用於連接數較少,或者線程廉價的情況,對C++來說第二種情況不符合。
IO multiplexing 複用的不是IO而是線程,是同步方式而不是異步方式。
IO multiplexing 要與非阻塞IO配合使用,不能與阻塞IO配合使用,因爲一旦某個socket fd 阻塞了,那麼IO multiplexing所在的線程就被阻塞類,其他歸該IO multiplexing 管理的socket fd也就被阻塞了。
那麼在讀取之前,先檢查是否可讀,是否就可以在IO複用線程中使用阻塞IO了呢?
答案是不可以,因爲:
- accept : 當有客戶端連接過來時,accept會返回listen fd 可讀, 但是在”變得可讀”和”accept”之間的這個時間窗口,客戶端有可能已經close了。
- select: Under Linux, select() may report a socket file descriptor as “ready for reading”, while
nevertheless a subsequent read blocks. This could for example happen when data has arrived
but upon examination has wrong checksum and is discarded. There may be other circumstances
in which a file descriptor is spuriously reported as ready. Thus it may be safer to use
O_NONBLOCK on sockets that should not block. (即使告訴你可讀,但是還是有可能block)