【发布时间】:2014-06-27 11:13:03
【问题描述】:
我以两种方式实现了多线程代码,但在这两种方式中都出现了错误。有人可以解释导致问题的原因吗?
在版本 1 中,我得到一个异常,说两个参数传递给 writekey 函数而不是一个。 在版本 2 中,其中一个线程读取空行,因此在处理空字符串时会引发异常。
我用的是锁,不应该防止多个线程同时访问函数或文件吗?
版本 1:
class SomeThread(threading.Thread):
def __init__(self, somequeue, lockfile):
threading.Thread.__init__(self)
self.myqueue = somequeue
self.myfilelock = lockfile
def writekey(key):
if os.path.exists(os.path.join('.', outfile)):
with open(outfile, 'r') as fc:
readkey = int(fc.readline().rstrip())
os.remove(os.path.join('.', outfile))
with open(outfile, 'w') as fw:
if readkey > key:
fw.write(str(readkey))
else:
fw.write(str(key))
def run(self):
while(True):
dict = self.myqueue.get()
self.myfilelock.acquire()
try:
self.writekey(dict.get("key"))
finally:
self.myfilelock.release()
self.myqueue.task_done()
populateQueue() # populate queue with objects
filelock = threading.Lock()
for i in range(threadnum):
thread = SomeThread(somequeue, filelock)
thread.setDaemon(True)
thread.start()
somequeue.join()
版本 2:
def writekey(key):
if os.path.exists(os.path.join('.', outfile)):
with open(outfile, 'r') as fc:
# do something...
os.remove(os.path.join('.', outfile))
with open(outfile, 'w') as fw:
# do something...
class SomeThread(threading.Thread):
def __init__(self, somequeue, lockfile):
threading.Thread.__init__(self)
self.myqueue = somequeue
self.myfilelock = lockfile
def run(self):
while(True):
dict = self.myqueue.get()
self.myfilelock.acquire()
try:
writekey(dict.get("key"))
finally:
myfilelock.release()
self.myqueue.task_done()
# Same as above ....
【问题讨论】:
-
如果您能发布例外情况将会很有帮助。
-
线程 Thread-2 中的异常:回溯(最近一次调用最后一次):...在运行 self.writekey(dict.get("key")) 文件中...,在 writekey 中 readkey = int(fc.readline().rstrip()) ValueError: int() 基数为 10 的无效文字:''
标签: python multithreading exception locking