未并行处理的Python线程

问题描述

我是Python的中间人,我想以并行模式运行几个相同的类实例,用于获取数据和为金融市场做出决策。为了继续我的想法,我运行下面的代码来看看Python是如何工作的,它似乎可以运行一次完整的第一类实例和第二类实例,我想并行运行它,我如何才能...? 以下是用于测试的一些示例代码..

import threading
import time

class thr(object):

  def __init__(self, name):
     self.name = name
     self.x = 0

  def run(self):
     for i in list(range(10)):
         self.x +=1
         print("something {0} {1}".format(self.name, self.x))
         time.sleep(1)            

F = thr("First")
S = thr("Second")

threading.Thread(target=F.run())
threading.Thread(target=S.run())

和结果如下...

something First 1
something First 2
something First 3
something First 4
something First 5
something First 6
something First 7
something First 8
something First 9
something First 10
something Second 1
something Second 2
something Second 3
something Second 4
something Second 5
something Second 6
something Second 7
something Second 8
something Second 9
something Second 10
Out[27]: <Thread(Thread-25, initial)>

解决方案

问题在这里:

threading.Thread(target=F.run())
threading.Thread(target=S.run())

target=接受可调用对象或NoneF.run()立即执行F.run,等待其完成,然后传递返回值(run()方法中的None)作为目标。

您想要这样的内容:

t1 = threading.Thread(target=F.run)
t2 = threading.Thread(target=S.run)
t1.start()
t2.start()

请注意,run后面没有括号

以下是带有建议更改的完整程序:

import threading
import time

class thr(object):

  def __init__(self, name):
     self.name = name
     self.x = 0

  def run(self):
     for i in list(range(10)):
         self.x +=1
         print("something {0} {1}".format(self.name, self.x))
         time.sleep(1)            

F = thr("First")
S = thr("Second")

t1 = threading.Thread(target=F.run)
t2 = threading.Thread(target=S.run)
t1.start()
t2.start()

和输出(Python3.6.1):

$ python sf.py
something First 1
something Second 1
something Second 2
something First 2
something Second 3
something First 3
something Second 4
something First 4
something Second 5
something First 5
something Second 6
something First 6
something Second 7
something First 7
something First 8
something Second 8
something First 9
something Second 9
something First 10
something Second 10

相关文章