RuntimeError:线程只能启动一次

时间:2017-10-28 17:24:50

标签: python multithreading

我正在制作一个简单的Python游戏。我试图解决以下错误:

  

RuntimeError:线程只能启动一次

我已尝试.cancel()计时器,但似乎没有工作,我在执行它之前已经发出if语句来查看计时器.is_alive。控制台正在ball_char = play_timer.start()抛出错误。

def playball(state):
 batbox = [["@", "@", "@", "@"], ["@", "#", "#", "#", "@"], ["@", "#", "#", "#", "@"], ["@", "#", "#", "#", "@"], ["@", "@", "@", "@"]]
 play = "playing"
 play_timer = Timer(1.0, pitch(batbox))
 end_timer = Timer(6.0, pitch_end(play))
 play_timer.cancel()
 end_timer.cancel()
 pstate = "idle"
 inning = 1
 outs = 0
 pscore =0
 cscore = 0
 strikes = 0
 ball_row = 0
 ball_col = 0
 ball_char = "."
 while play == "playing":
     batbox = [["@", "@", "@", "@"], ["@", "#", "#", "#", "@"], ["@", "#", "#", "#", "@"], ["@", "#", "#", "#", "@"], ["@", "@", "@", "@"]]
     os.system('cls')  # on windows
     os.system('clear') # on linux / os x
     # Playing the game
     print "Press enter to start / hit the pitch"
     print_grid(batbox)
     input = raw_input("")
     pstate = "hitting"
     # Hitting
     if pstate == "hitting":
         ball_row = random_row(batbox) 
         ball_col = random_col(batbox)
         end_timer.start()
         while pstate == "hitting":
             batbox[ball_row][ball_col] = ball_char
             if play_timer.is_alive():
                 play_timer.cancel()
             else:
                 ball_char = play_timer.start()
 else:
     play_timer.cancel()
     end_timer.cancel()
     state = "mainmenue"
     return state

1 个答案:

答案 0 :(得分:3)

documentation for Threading.Thread(其中Timer是子类)声明:

  

start()开始线程的活动。

     

每个线程对象最多只能调用一次。它安排了   object的run()方法在一个单独的控制线程中调用。

     

如果在on上多次调用此方法将引发RuntimeError   相同的线程对象。

即使取消线程(或计时器),仍然无法再次调用start()。您需要创建一个新的线程/计时器对象,否则这是一个错误。