执行非块写入时出现问题

Issue when performing non-block writing

我写了下面的代码来理解非阻塞写是如何操作的:

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()

如您所见,我正在创建 takeAnap() 以在处理循环时激活,以便我可以说服自己写入是在没有阻塞的情况下执行的!但是,循环仍然阻塞并且该方法直到完成才执行。我不确定我的理解是否错误,但据我所知,非阻塞操作允许您在处理写入时执行其他任务。那是对的吗?如果是这样,请问我的代码哪里有问题!

谢谢。

我认为您误解了 O_NONBLOCK 标志的用途。这是标志 实际上 的作用:

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.

摘自https://www.gnu.org/software/libc/manual/html_node/Open_002dtime-Flags.html

所以,flag没有指定non-blockingwrite,而是non-blockingopen。写的还是串行,阻塞,慢