此错误的常见原因是什么? (不看代码)
我用谷歌搜索过,但似乎没有找到任何关于此类错误的引用资料。
我最初的猜测是(通过查看错误消息),有一个 thr/proc 正在对对象执行某些操作,而另一个 thr/proc 正试图关闭它。
文件对象是否有类似锁的机制?
最佳答案
文件
-目标代码的某些部分允许多线程——它们发布GIL在操作期间,即 python-2.7.9/Objects/fileobject.c 中的 file_read()
包含以下行:
FILE_BEGIN_ALLOW_THREADS(f)
errno = 0;
chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
buffersize - bytesread, f->f_fp, (PyObject *)f);
interrupted = ferror(f->f_fp) && errno == EINTR;
FILE_END_ALLOW_THREADS(f)
FILE_BEGIN_ALLOW_THREADS
增加引用计数器,在 close()
端检查:
/*
* These macros release the GIL while preventing the f_close() function being
* called in the interval between them. For that purpose, a running total of
* the number of currently running unlocked code sections is kept in
* the unlocked_count field of the PyFileObject. The close() method raises
* an IOError if that field is non-zero. See issue #815646, #595601.
*/
#define FILE_BEGIN_ALLOW_THREADS(fobj) \
{ \
fobj->unlocked_count++; \
Py_BEGIN_ALLOW_THREADS
我试图用下面的脚本重现这种行为,但它使我的解释器出现段错误:
import sys
from threading import Thread
def read():
sys.stdin.read(10)
t = Thread(target = read)
t.start()
sys.stdin.close()
t.join()
无论如何,您可以使用 threading
模块中的 Lock
对象:
import sys
from threading import Thread, Lock
stdin_lock = Lock()
def read():
with stdin_lock:
sys.stdin.read(10)
t = Thread(target = read)
t.start()
with stdin_lock:
sys.stdin.close()
t.join()
关于python - IO错误 : close() called during concurrent operation on the same file object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29890603/