- 论坛徽章:
- 0
|
正在学python的多线程。写了个多线程的读取文件。不知道为什么总是有问题。以下是代码:
def readFile(fn):
time.sleep(1)
if mutex.acquire():
line=fn.readline()
if line:
print line
mutex.release()
else:
pass
else:
pass
if __name__ == '__main__':
# global offset
offset=0
global mutex
mutex=threading.Lock()
fn=open('/tmp/ttt.txt','rU')
threads=[]
for i in range(5):
t=threading.Thread(target=readFile,args=(fn,))
threads.append(t)
t.start()
fn.close()
print 'The python script exit.'
最后总得到错误代码
File "3.py", line 12, in readFile
line=fn.readline()
ValueError: I/O operation on closed file
这个script的目的是多线程逐行读文件。
我也考虑过在readFile函数中加入offset,但总得不到我想要的结果。
望高手指教。谢谢。
|
|