47. Nio (Io model (multiplexing))

Nio (Io model (multiplexing))

Multiplexing, where the select is blocked, and then the data is copied after the read event (also blocked)

 

Multiplexing and blocking IO comparison

  1. blocking io

Imagine a scenario where we have multiple channels, channel1 and channel2, if we are single-threaded in a loop to process multiple channel requests (ch1 is read, ch2 is accept event). After Channel1 sends data and triggers the read event, channel2 connects to the event, but at this time, if 1 reads again, then it will not work. The previous accept event of 2 has not completed the return, (only after 2 establishes the connection and returns) 1 can perceive the read, read it again.

 

Blocking io: When a channel is waiting for an event connection, other channels cannot do read operations. (When one person is doing one thing, others cannot do it)

  1. Multiplexing (initially a single thread plus selector)

 

After the select is blocked (waiting for events), a bunch of events are returned (instead of blocking io one event at a time), and then let him process all of them in the following loop. So he doesn't have to wait for the connection and data in front (select is already waiting for the event to complete, we just need to run down immediately after selecting (no need to wait)). We do all the waiting while waiting for the event. (If it is single-threaded, although a batch of events is returned and processed in a loop, it is still processed one by one when processing, and blocking one will also block later, so we add multiple threads to process events separately)

! ! ! Understand it this way, blocking io is to wait for specific events before executing (immediately) (execution takes time), and multiplexing is to execute events later (not immediately) (there is a copy Go to the collection and then go to the collection traversal event operation), you go to traverse the previously copied collection to get the event you want and then process it. (It takes time for us to copy. At this time, the event comes again, so he will copy it again. Then traverse (iterator) copy collection and execute)

Guess you like

Origin blog.csdn.net/logtcm4/article/details/127851413