gpt4 book ai didi

Python - 线程同时打印弄乱了文本输出

转载 作者:行者123 更新时间:2023-12-03 12:44:52 26 4
gpt4 key购买 nike

我在一个应用程序中使用 4 个线程,这些线程返回我想打印给用户的文本。
因为我想避免线程独立打印这些文本,所以我创建了一个类来管理它......

我不知道我在这里做错了什么,但它仍然无法正常工作。

您可以在下面看到的代码:

from threading import Thread
import time
import random

class Creature:

def __init__(self, name, melee, shielding, health, mana):
self.name = name
self.melee = melee
self.shielding = shielding
self.health = health
self.mana = mana

def attack(self, attacker, opponent, echo):
while 0 != 1:
time.sleep(1)
power = random.randint(1, attacker.melee)
resistance = random.randint(1, opponent.shielding)
resultant = power - resistance
if resistance > 0:
opponent.health -= resistance
if opponent.health < 0:
msg = opponent.name, " is dead"
echo.message(msg)
quit()
else:
msg = opponent.name, " lost ", resistance, " hit points due to an attack by ", attacker.name
echo.message(msg)

def healing(self, healed, echo):
while 0 != 1:
time.sleep(1)
if self.mana >= 25:
if healed.health >= 0:
if healed.health < 50:
life = random.randint(1, 50)
self.mana -= 25
healed.health += life
if healed.health > 100:
healed.health = 100
msg = healed.name, " has generated himself and now has ", self.health, " hit points"
echo.message(msg)
else:
quit()

class echo:
def message(self, msg):
print msg

myEcho = echo()

Monster = Creature("Wasp", 30, 15, 100, 100)
Player = Creature("Knight", 25, 20, 100, 100)

t1 = Thread(target = Player.attack, args = (Monster, Player, myEcho))
t1.start()
t2 = Thread(target = Monster.attack, args = (Player, Monster, myEcho))
t2.start()
t3 = Thread(target=Player.healing(Player, myEcho), args=())
t3.start()
t4 = Thread(target=Monster.healing(Monster, myEcho), args=())
t4.start()

在这里你可以看到困惑的输出:
*('Wasp'('Knight', ' l, ' lost ', ost 13, ' hit points ', 4, due to an attack by '' hi, 'Waspt poi')nts d
ue to an attack by ', 'Knight')
('Wasp', ' lost ', 12, ' hit points due to an attack by ', 'Knight')
('Knight', ' lost ', 17, ' hit points due to an attack by ', 'Wasp')
('Wasp', ' lost ', 6, ' hit points due to an attack by ', 'Knight'('Knight')
, ' lost ', 1, ' hit points due to an attack by ', 'Wasp')
('Wasp', ' lost ', 5, ' hit points due to an attack by ', 'Knight')
('Knight', ' lost ', 13, ' hit points due to an attack by ', 'Wasp')
(('Wa'Knighsp't', , ' los' lostt ' ', , 32, ' hit points due to an attack by ', 'Knight')
, ' hit points due to an attack by ', 'Wasp')*

你们知道如何解决这个问题吗?

谢谢!

最佳答案

使用 threading.Semaphore 以确保不会有任何冲突:

screenlock = Semaphore(value=1)   # You'll need to add this to the import statement.

然后,在您调用 echo.message 之前,插入此行以获得输出权:
screenlock.acquire()

然后在您调用 echo.message 后使用此行以便允许另一个线程打印:
screenlock.release()

关于Python - 线程同时打印弄乱了文本输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26688424/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com