首页 > 解决方案 > Python:运行并发增量函数时出现问题

问题描述

我正在 Mu 上开发类似 Cookie Clicker 的增量游戏脚本。每次你输入一个'。它将名为“dots”的变量加一。但是,我无法同时运行这个函数,该函数每秒将“点”变量增加一个。

import threading
import time
dots = 0

def func1():
    global dots
    while True:
        user_input = input() 
        if user_input == '.':
            dots = dots + 1
            print(dots)

def func2():
    global dots
    while True:
        time.sleep(1)
        dots = dots + 1
        print(dots)

func1_thread = threading.Thread(target=func1)
func2_thread = threading.Thread(target=func2)

if __name__ == '__main__':
    func1_thread.start()
    func2_thread.start()

此代码会导致每个交替的“。”出现语法错误。用户输入:

文件“”,第 1 行

^
SyntaxError: 无效的语法

提前感谢任何帮助我的人。

(修复了问题,我运行的python版本是3.6,所以我在3.9版本上切换到pycharm,效果很好。)

标签: pythonpython-3.xmultithreadingfunctionconcurrency

解决方案


推荐阅读