以下代碼錯誤偶爾出現一次。如果我只啓動一個進程,它工作正常。但我不斷增加進程的數量,可能是11,並開始拋出一個錯誤。python multiprocessing TypeError:'int'對象不可迭代
try:
num_workers = int(sys.argv[1])
except:
num_workers = 1
someval = 10
def do_work(in_queue,x):
i = 0
while True:
item = in_queue.get()
line_no, line = item
# exit signal
if line == None:
if i > 0 :
work.put(i,)
# work.put(i)
return
else:
print "value from work " + line.rstrip('\n')
i = i + 1
if __name__ == "__main__":
manager = Manager()
work = manager.Queue(num_workers)
someval = 20
print " Number of workers is " + str(num_workers)
pool = []
for i in xrange(num_workers):
p = Process(target=do_work, args=(work,someval))
p.start()
pool.append(p)
with open("/home/jay/scripts/a.txt") as f:
iters = itertools.chain(f, (None,)*num_workers)
for num_and_line in enumerate(iters):
work.put(num_and_line)
x = 0
for p in pool:
p.join()
文件/home/jay/scripts/a.txt有10行。
如果我做
./x.py 7
Number of workers is 7
value from work 1
value from work 2
value from work 3
value from work 4
value from work 5
value from work 6
value from work 7
value from work 8
value from work 9
value from work 10
x is 0
all done
./x.py 11
Number of workers is 11
value from work 1
value from work 2
value from work 3
value from work 4
value from work 5
value from work 6
value from work 7
value from work 8
value from work 9
value from work 10
Process Process-11:
Traceback (most recent call last):
File "/usr/lib64/python2.7/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/usr/lib64/python2.7/multiprocessing/process.py", line 114, in run
self._target(*self._args, **self._kwargs)
File "./x.py", line 18, in do_work
line_no, line = item
TypeError: 'int' object is not iterable
x is 0
all done
在第18行之前加上'print(repr(item))'這樣你就可以知道這個值是什麼 –