请教多线程的readline
正在学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,但总得不到我想要的结果。
望高手指教。谢谢。
多线程读文件的意义是啥? 我写了一个script,在网上摘取了proxy写入一个文件中,现在想多线程来测试这些proxy的速度。得把这些proxy ip逐行读出来,当参数发给下一个函数。 回复 1# hstking
主线程提前推出了啊,在"fn.close()"前加上:for t in threads:
t.join() 是这个原因,非常感谢。找了好久都没找到。
页:
[1]