在Python多进程中创建线程

2024-04-28 21:53:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我在为一个游戏编写代码,AI作为线程运行。它们与相关信息一起存储在一个列表中,这样当它们的角色“死亡”时,只需将它们从活动AI列表中移除,就可以有效地将它们从游戏中移除。你知道吗

当控制播放器的tkinter窗口在主线程中运行时,控制它们的线程最初是从另一个线程中调用的——然而,AI线程导致主线程速度减慢。在寻找一种降低创建AI的线程优先级的方法之后,我发现我必须使用多处理过程而不是穿线。穿线,然后改变它的精细度-但是当我尝试这样做时,AI线程不起作用。运行此函数的函数在class AI()中定义:

def start():
    '''
    Creates a process to oversee all AI functions
    '''
    global activeAI, AIsentinel, done
    AIsentinel=multiprocessing.Process(target=AI.tick,args=(activeAI, done))
    AIsentinel.start()

以及

def tick(activeAI, done):
    '''
    Calls all active AI functions as threads
    '''
    AIthreads=[]
    for i in activeAI:
        # i[0] is the AI function, i[1] is the character class instance (user defined)
        # and the other list items are its parameters.
        AIthreads.append(threading.Thread(name=i[1].name,target=lambda: i[0](i[1],i[2],i[3],i[4],i[5])))
        AIthreads[-1].start()
    while not done:
        for x in AIthreads:
            if not x.is_alive():
                x.join()
                AIthreads.remove(x)
                for i in activeAI:
                    if i[1].name==x.name:
                        AIthreads.append(threading.Thread(name=i[1].name,target=lambda: i[0](i[1],i[2],i[3],i[4],i[5])))
                        AIthreads[-1].start()

这些线程的输出应该显示在stdout中,但是在运行程序时,什么都没有出现——我假设这是因为线程没有启动,但是我不能判断这是否只是因为它们的输出没有显示。我想找到一个方法让这个解决方案工作,但我怀疑这个解决方案太难看,不值得修复,或者根本无法修复。你知道吗

如果这像我担心的那样可怕,我也会完全接受解决这个问题的新方法。你知道吗

我在Windows10上运行这个。提前谢谢。你知道吗

编辑:

实际的print语句在另一个线程中—当AI执行一个操作时,它会将描述其操作的字符串添加到队列中,然后由另一个线程打印出来(好像我没有足够的字符串)。例如:

battle_log.append('{0} dealt {1} damage to {2}!'.format(self.name,damage[0],target.name))

由以下人员读出:

def battlereport():
    '''
    Displays battle updates.
    '''
    global battle_log, done
    print('\n')
    while not done:
        for i in battle_log:
            print(i)
            battle_log.remove(i)

Tags: 方法nameinlogtargetfordef线程