PYTHON无差错跳转过程中的多处理
问题描述
我有以下代码,它的行为非常奇怪。
class A:
def __init__(self):
self.lock = Lock()
self.process_list = []
self.event_list = []
def run(self):
self.process_list = []
counter = 0
n = 0
while (n<1000):
n += 1
print("in while again")
self.lock.acquire()
print('after acquired lock')
self.lock.release()
self.event_list.append(Event())
print('add event')
p = Process(target=workerEmulator().run,
args=(self.lock, self.event_list[counter]))
print('create process')
self.process_list.append(p)
print('add process')
self.event_list[counter].clear()
counter += 1
print("about to start process")
print("n="+str(n))
p.start()
print("new process started")
print(": main process, active_children: " + str(multiprocessing.active_children()))
del_list = [] # the list for storing index of the process/event to delete
for i in range(len(self.event_list)):
if (self.event_list[i].is_set()):
self.process_list[i].join()
print("one process finished, its exit code: " + str(self.process_list[i].exitcode))
print("this process is alived or not? " + str(self.process_list[i].is_alive()))
del_list.append(i)
del_list.sort(reverse=True)
for i in del_list:
del self.event_list[i]
del self.process_list[i]
counter -= 1
time.sleep(0.1)
for p in self.process_list:
p.join()
print("one process finished, its exit code: " + str(p.exitcode))
print("this process is alived or not? " + str(p.is_alive()))
class workerEmulator:
def __init__(self):
pass
def run(self, lock, event):
print("a new process")
self.lock = lock
self.event = event
time.sleep(20)
print("after sleep")
self.lock.acquire()
print("in lock")
self.lock.release()
self.event.set()
if __name__ == '__main__':
a = A()
a.run()
正如我所想,每条print语句都应该执行1000次。然而,从来不是这样的,总是有几次遗漏,然后如果我们看n,我注意到n会跳过某个数字,例如,……N=798...n=799...n=801...n=802...(n=800人失踪)。我不明白为什么会这样,有人能帮帮忙吗?
解决方案
查看Matt的评论,该问题是由子输出与父输出混合引起的。
相关文章