我用两种方法实现了多线程代码,但在这两种方法中我都遇到了一个错误。有人能解释一下问题的原因吗?在
在版本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:
^{pr2}$
在版本1中,
def writekey(key)
应该以“self”作为第一个参数声明,即版本2中的问题就不那么清楚了。我假设在读取
^{pr2}$outfile
时正在读取空行。这是正常的,它表示已到达文件结尾。通常情况下,您只需跳出读取循环。通常最好在for
循环中逐行读取文件,例如for循环将在到达文件结尾时自然终止。在
相关问题 更多 >
编程相关推荐