Non-Blocking IO - Programming Model

In a non-blocking IO programming model, a stream blocked by available data channels, as shown below,

in python,

while True: readers, _, _ = select.select([sys.stdin, sock], [], []) # blocked select() for reader in readers: if reader is sock: print(sock.recv(1000).decode('utf-8')) else: msg = sys.stdin.readline() sock.send(msg.encode('utf-8')) 

in java,

  public void run() { while(true){ try{ executeCycle(); } catch(IOException e){ e.printStackTrace(); } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } public void executeCycle() throws IOException { takeNewSockets(); readFromSockets(); writeToSockets(); } 

In a non-blocking I / O programming model, the execution flow usually follows an infinite loop pattern with the primary (sole) responsibility for finding available data channels (ready) and performing I / O with an available channel.


In a scenario where all the channels are busy (for the duration), does the non-blocking I / O programming model make a thread that runs nio with / without an infinite loop also to perform another CPU-related task in the same thread, meanwhile?

-1
source share
2 answers

These APIs usually allow you to specify a timeout for the selection step. That is, the amount of time to wait until any of the channels is ready, returning an empty set, if no channel is ready for a timeout. You can also make an immediate choice that returns immediately.

in python:

 while True: readers, _, _ = select.select([sys.stdin, sock], [], [], 0) # non-block select # readers could be an empty list if readers: for reader in readers: if reader is sock: print(sock.recv(1000).decode('utf-8')) else: msg = sys.stdin.readline() sock.send(msg.encode('utf-8')) else: some_other_operations() # but only when no channel is ready 

The Java Selector class has similar methods, such as selectNow() and select(long timeout) , which you can use.

+1
source

I do not think it is easy to perform other operations in the same thread at the same time. You will need to call the code to perform these other operations. How do you guarantee that management will return to validating entries in a reasonable amount of time?

But if you have a separate thread to handle other operations, then the runtime system will assign these threads to run whenever resources are available. If you use something like Thread.sleep (100) in a busy cycle, this will make sure that this busy cycle will not use so many resources that other things will work at the same time without doing anything special.

You will need to make sure that all resources that are shared by the input validation thread and other threads are processed in streaming mode.

0
source

Source: https://habr.com/ru/post/971872/


All Articles