如何同步运行python函数? [英] How to run python functions synchronously?

查看:40
本文介绍了如何同步运行python函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为 Python 构建一个 twitch 聊天机器人,其中包含一些自定义游戏,我正在添加这些游戏以供观众在观看我的直播时使用.我目前的目标是做一个骰子决斗游戏(2人游戏,谁得到最高的数字就赢得赌注的总和).为了比赛,我希望双方玩家在允许比赛继续之前接受比赛,但我也想实现比赛计时器,以便如果其他用户在计时器到期之前不接受比赛,它将取消比赛.我想为每个游戏创建一个新线程并扫描以查看游戏是否已过期,但需要它们与聊天机器人的其余部分并行运行,否则我一次只能有 1 个游戏,并且当它发生时,机器人的其余部分将停止.

我已经尝试过使用 Python 附带的多线程模块创建两个进程并启动它们.我也尝试过使用线程模块,它提供了相同的结果.这是我编写的多线程代码,试图使其工作.

processes = []# Tick 有一个基本的打印语句,和一个用于测试的睡眠语句.# 在没有睡眠的情况下尝试,并使用 for 循环打印测试"100 次,以查看睡眠是否导致问题tickprocess = multiprocessing.Process(target=tick())processes.append(tickprocess)# Main 初始化设置并启动聊天机器人chatbotprocess = multiprocessing.Process(target=main())进程.附加(聊天机器人进程)对于进程中的项目:item.start()

它的作用是启动滴答进程,但它在启动聊天机器人进程之前等待它完成,这与我想要做的相反,因为我可以只调用滴答函数,然后调用主函数得到相同的结果.我是否误解了这些模块的用途?最终目标是在收到骰子命令时启动一个游戏线程,但仍然允许机器人同步工作并处理其他命令和游戏(所有游戏都立即运行或接近到立即运行,冲突不是问题).

解决方案

tick()main() 是函数调用.所以实际上你调用函数tick,得到它的result(大概是None),然后将该结果传递给multiprocessing.Process().

你想要的是将tick(以及后来的main)函数传递给multiprocessing.Process():

tickprocess = multiprocessing.Process(target=tick)

如果你仔细查看文档(https://docs.python.org/3.4/library/multiprocessing.html?highlight=process#the-process-class),它就在第一个例子中:

<块引用>

from multiprocessing import Process定义 f(名称):打印('你好',姓名)如果 __name__ == '__main__':p = Process(target=f, args=('bob',)) # <------ target=f, not target=f()p.start()p.join()

I've been building a twitch chatbot for Python that has some custom games that I'm adding to have something for viewers to use while they watch my stream. My current goal is to make a dice duel game (2 player game where whoever gets the highest number wins the sum of the bets made). In order to play, I want both players to accept the match before allowing it to continue, but I also want to implement a match timer so that if the other user doesn't accept the match before a timer expires, it will cancel the game. I want to make a new thread for each game and scan to see if the game has expired or not, but need them to run in parallel to the rest of the chatbot, or else I can only have 1 game at a time, and the rest of the bot will grind to a halt when it happens.

What I've already tried is this using the multithreading module included with Python by making two processes, and starting them. I've also tried using the threading modules, and it provides the same result. Here is the multithreading code I wrote to attempt to make it work.

processes = []
# Tick has a basic print statement, and a sleep statement for testing.
# Tried without the sleep, and used a for loop to print "test" 100 times as well to see if the sleep was causing the issue
tickprocess = multiprocessing.Process(target=tick()) 
processes.append(tickprocess)

# Main initializes settings and starts the chatbot
chatbotprocess = multiprocessing.Process(target=main()) 
processes.append(chatbotprocess)

for item in processes:
    item.start()

What this does is it will start the tick process, but it waits for it to complete before starting the chatbot process which is the opposite of what I want to do since I could just call the tick function and then the main function to get the same result. Am I misunderstanding what these modules are for? The end goal is to start a game thread when the dice command is received, but still allow the bot to work synchronously and handle other commands and games (all games to this point run instantly or close enough to instantly that conflicts are not an issue).

解决方案

tick() and main() are function calls. So practically you call function tick, get its result (presumably None), then pass that result to multiprocessing.Process().

What you want instead is passing the tick (and later main) function to multiprocessing.Process():

tickprocess = multiprocessing.Process(target=tick)

If you carefully check the documentation (https://docs.python.org/3.4/library/multiprocessing.html?highlight=process#the-process-class), it is right there in the first example:

from multiprocessing import Process

def f(name):
    print('hello', name)

if __name__ == '__main__':
    p = Process(target=f, args=('bob',))  # <------ target=f, not target=f()
    p.start()
    p.join()

这篇关于如何同步运行python函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆