我在线程和
Python中的tempfile模块有一个有趣的问题.在线程退出之前,某些东西似乎没有得到清理,而且我正在针对打开的文件限制运行. (这是在OS X 10.5.8,Python 2.5.1上.)
然而,如果我复制tempfile模块正在做什么(不是所有的安全检查,而只是生成文件描述符然后使用os.fdopen来生成文件对象)我没有问题.
在将此作为Python的错误提交之前,我想我会在这里查看,因为我更有可能做了一些巧妙的错误.但是,如果我是,那一天试图解决它并没有让我到任何地方.
- #!/usr/bin/python
- import threading
- import thread
- import tempfile
- import os
- import time
- import sys
- NUM_THREADS = 10000
- def worker_tempfile():
- tempfd,tempfn = tempfile.mkstemp()
- tempobj = os.fdopen(tempfd,'wb')
- tempobj.write('hello,world')
- tempobj.close()
- os.remove(tempfn)
- time.sleep(10)
- def worker_notempfile(index):
- tempfn = str(index) + '.txt'
- # The values I'm passing os.open may be different than tempfile.mkstemp
- # uses,but it works this way as does using the open() function to create
- # a file object directly.
- tempfd = os.open(tempfn,os.O_EXCL | os.O_CREAT | os.O_TRUNC | os.O_RDWR)
- tempobj = os.fdopen(tempfd,world')
- tempobj.close()
- os.remove(tempfn)
- time.sleep(10)
- def main():
- for count in range(NUM_THREADS):
- if count % 100 == 0:
- print('opening thread %s' % count)
- wthread = threading.Thread(target=worker_tempfile)
- #wthread = threading.Thread(target=worker_notempfile,args=(count,))
- started = False
- while not started:
- try:
- wthread.start()
- started = True
- except thread.error:
- print('Failed starting thread %s; sleeping' % count)
- time.sleep(3)
- if __name__ == '__main__':
- main()
如果我在worker_notempfile行处于活动状态并且worker_tempfile行注释掉的情况下运行它,它将运行完成.
反过来(使用worker_tempfile)我收到以下错误:
- $python threadtempfiletest.py
- opening thread 0
- opening thread 100
- opening thread 200
- opening thread 300
- Exception in thread Thread-301:
- Traceback (most recent call last):
- File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py",line 460,in __bootstrap
- File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.py",line 440,in run
- File "threadtempfiletest.py",line 17,in worker_tempfile
- File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/tempfile.py",line 302,in mkstemp
- File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/tempfile.py",line 236,in _mkstemp_inner
- OSError: [Errno 24] Too many open files: '/var/folders/4L/4LtD6bCvEoipksvnAcJ2Ok+++Tk/-Tmp-/tmpJ6wjV0'
我有什么想法我做错了吗?这是Python中的一个错误,还是我头脑发热?
更新2009-12-14:
我想我找到了答案,但我不喜欢它.由于没有人能够复制这个问题,我去办公室寻找机器.除了我的机器,它传递了一切.我在Mac上使用与我使用的相同软件版本进行了测试.我甚至用我所拥有的完全相同的硬件和软件配置来寻找桌面G5 – 结果相同.两个测试(使用tempfile和没有tempfile)都成功了.
对于踢,我下载了Python 2.6.4,并在我的桌面上尝试了它,我的系统上的模式与Python 2.5.1相同:tempfile失败,并且notempfile成功.
这让我得出结论,我的Mac上出现了一些东西,但我肯定无法弄清楚是什么.欢迎任何建议.