多线程卡住 - 在条件变量中怀疑错误

时间:2017-11-22 22:41:03

标签: python multithreading locking python-multithreading ant-colony

我正在测试一个使用多个线程运行的蚁群优化(ACO)软件(每个创建一个ant的1个)。

在允许下一次迭代开始之前,每个ACO迭代都应该等待所有线程完成。我用线程模块中的“condition()”来做这个。

由于蚂蚁共享一种pherormone矩阵,因此该矩阵的读写也受到线程模块的锁定。

现在<问题>的描述

我运行该函数并在每次迭代时打印一些东西。有时,并非总是如此,它会停止执行函数,也就是说,它会停止打印,这意味着迭代永远不会完成。

老实说,我现在不知道为什么会发生这种情况,我希望任何能让我走上正轨的答案。如果我不得不猜测我会说条件变量没有被正确调用,或类似的东西。但是我不确定,我也觉得奇怪,这种情况有时只会发生。

以下是相关功能。 ACO首先调用start()函数。这会创建N个线程,完成后会调用update()。这个更新函数在被调用N次时调用notify,它允许start()继续进程,最后开始下一次迭代。我还发布了每个线程的run方法。

值得一提的是,如果没有守护进程操作,则几乎不会发生错误。通过守护进程操作,它几乎总是发生(我也发现奇怪)。 最后,错误不会始终在同一次迭代中发生。

    def start(self):
        self.ants = self.create_ants()
        self.iter_counter = 0

        while self.iter_counter < self.num_iterations:
            print "START ACQUIRED"
            self.cv.acquire()
            print "calling iteration"
            self.iteration()
            #CV wait until all ants (threads) finish and call update, which
            #calls notify(), and allow continuation
            while not self.iter_done:
                print "iter not complete, W8ING"
                self.cv.wait()
            print "global update "
            self.global_update_with_lock()
            print "START RELEASED"
            self.cv.release()

def update(self, ant):
    lock = Lock()
    lock.acquire()

    print "Update called by %s" % (ant.ID,)
    self.ant_counter += 1

    self.avg_path_cost += ant.path_cost

    # book-keeping
    if ant.path_cost < self.best_path_cost:
        self.best_path_cost = ant.path_cost
        self.best_path_mat = ant.path_mat
        self.best_path_vec = ant.path_vec
        self.last_best_path_iteration = self.iter_counter

    #all threads finished, call notify
    print "ant counter"
    print self.ant_counter
    if self.ant_counter == len(self.ants):
        print "ants finished"
        #THIS MIGHT CAUSE PROBLEMS (no need to notify if its no one waiting)
        self.best_cost_at_iter.append(self.best_path_cost)
        self.avg_path_cost /= len(self.ants)

        self.cv.acquire()
        self.iter_done = True
        self.cv.notify()
        self.cv.release()

    lock.release()

    # overide Thread's run()
    def run(self):
        graph = self.colony.graph
        while not self.end():
            # we need exclusive access to the graph
            graph.lock.acquire()
            new_node = self.state_transition_rule(self.curr_node)
            self.path_cost += graph.delta(self.curr_node, new_node)

            self.path_vec.append(new_node)
            self.path_mat[self.curr_node][new_node] = 1  #adjacency matrix representing path

            #print "Ant %s : %s, %s" % (self.ID, self.path_vec, self.path_cost,)

            self.local_updating_rule(self.curr_node, new_node)
            graph.lock.release()

            self.curr_node = new_node

        # close the tour
        self.path_vec.append(self.path_vec[0])

        #RUN LOCAL HEURISTIC
        if self.daemon == True:
            try:
                daemon_result =  twoOpt(self.path_vec, graph.delta_mat)
                d_path, d_adj = daemon_result['path_vec'], daemon_result['path_matrix']
                self.path_vec = d_path
                self.path_mat = d_adj
            except Exception, e:
                print "exception: " + str(e)
                traceback.print_exc()

        self.path_cost += graph.delta(self.path_vec[-2], self.path_vec[-1])
        # send our results to the colony
        self.colony.update(self)
        #print "Ant thread %s terminating." % (self.ID,)
        
        # allows thread to be restarted (calls Thread.__init__)
        self.__init__(self.ID, self.start_node, self.colony, self.daemon, self.Beta, self.Q0, self.Rho)

解决问题的方法: 首先,根据这里的评论,我更正了等待条件变量的错误。 其次,它有时仍然悬空,这是由于线程计数器更新中的一个有点错误的错误。 解决方案是将计数器从int更改为长度为num_threads且满为0的数组,其中每个线程更新其在列表中的位置。当所有线程完成时,计数器数组应该都是1。目前工作正常。

0 个答案:

没有答案