Ahmad
Ahmad

Reputation: 85

Issue when performing non-block writing

I wrote the following code to understand how nonblocking write is operated:

import os, time

def takeAnap():
    print('I am sleeping a bit while it is writing!')
    time.sleep(50)

fd = os.open('t.txt', os.O_CREAT | os.O_NONBLOCK)
for i in range(100):
    # Non-blocking write
    fd = os.open('t.txt', os.O_APPEND | os.O_WRONLY | os.O_NONBLOCK)
    os.write(fd, str(i))
    os.close(fd)
    time.sleep(2)
takeAnap()

As you can see, I am creating takeAnap() to be activated while the loop is being processed so that I can convince my self that the writing is performed without blocking! However, the loop still blocks and the method is not performed until finishing. I am not sure if my understanding is wrong but as far as I know, non-blocking operation allows you to do other tasks while the writing is being processed. Is that correct? If so, kindly where is the problem in my code!

Thank you.

Upvotes: 1

Views: 250

Answers (1)

cs95
cs95

Reputation: 402603

I think you misunderstand what the O_NONBLOCK flag is used for. Here's what the flag actually does:

This prevents open from blocking for a “long time” to open the file. This is only meaningful for some kinds of files, usually devices such as serial ports; when it is not meaningful, it is harmless and ignored.

Excerpt from https://www.gnu.org/software/libc/manual/html_node/Open_002dtime-Flags.html.

So, the flag does not specify non-blocking write, but non-blocking open. The writing is still serial, and blocking, and slow.

Upvotes: 1

Related Questions