Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In non blocking IO programming model, a thread blocked on data available 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 Non-blocking IO programming model, execution flow generally follows the pattern of infinite-loop with the main(only) responsibility to find the data available channels(ready) and perform IO with the available channel.


In a scenario, where all channels are busy(for a duration), Does non-blocking IO programming model allow a thread that perform nio with/without infinite loop also to perform another CPU-bound task in same thread, for a meantime?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
177 views
Welcome To Ask or Share your Answers For Others

1 Answer

These APIs usually allow you to specify a timeout for the selection step. That is, the amount of time to wait for any of the channels to be ready, returning an empty set if no channel became ready in the timeout. You can also do a non-block selection 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

Java's Selector class has similar methods like selectNow() and select(long timeout) that you can use.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...