首页 > 解决方案 > 将正在运行的线程引用到 python 中的新线程类中

问题描述

看起来这工作正常,但我不能停止思考在 Python 中使用多线程是否正确或被认为是最佳实践,因为它看起来很简单(我没有在 Python 中进行并行编程的经验)而且可能是当这两个类变得更复杂时,遗漏了一些东西或有潜在的问题。我会很感激任何建议。谢谢!

class Runner1(threading.thread):
    def __init__(self): 
       threading.Thread.__init__(self)
       self.n = 0
    def run(self):
       while self.n < 100:
         time.sleep(10)
         self.n += 1


thread1 = Runner1()
thread1.start()

class Runner2(threading.thread):
    def __init__(self, runner): 
       threading.Thread.__init__(self)
       self.runner = runner
    def run(self):
       while True:
          print(self.runner.n)
          time.sleep(10)

thread2 = Runner2(thread1)
thread2.start()

标签: pythonmultithreading

解决方案


将对象从一个线程传递Thread到另一个线程很好。但是,nin方法Runner1的增量run()不是原子的,所以我建议在对n. (虽然目前只有一个线程在修改它,但一旦事情变得更复杂一点,除非变量受到保护,否则它将成为一个问题。)


推荐阅读