python中的多处理跳转过程没有错误

时间:2016-03-14 13:58:56

标签: python python-multiprocessing

我有以下代码,这很奇怪。

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缺失)。我不明白为什么会这样,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

参见Matt的评论,问题是由父输出的子输出混合引起的。