简体   繁体   English

Python:for循环内的多线程

[英]python: multi-threading inside a for loop

I have to solve a system of ODE using a fix time step. 我必须使用固定时间步骤解决ODE系统。 At each time step, I must compute the output of a number of similar equations (I am programming a neural network and I must compute the value of each neuron. Those neurons are represented by a system of ODE). 在每个时间步长上,我必须计算出许多类似方程式的输出(我正在对神经网络进行编程,并且必须计算每个神经元的值。这些神经元由ODE系统表示)。 Thus I would like to parallel the computations inside the loop. 因此,我想在循环内部并行计算。 I tried using the threading package but I should have done something wrong because it does not work... (In the following code, I skip the generation of the input for clarity) 我尝试使用线程包,但是我应该做错了一些事情,因为它不起作用...(在以下代码中,为清楚起见,我跳过了输入的生成)

class EBNMCPU(threading.Thread):
  def __init__(self, threadID, Ts, OnDir):
    self.threadID = threadID
    self.Neuron=NM.EBN(Ts,Dir=OnDir)
    threading.Thread.__init__(self)
  def run(self,Glu=[np.array([1.0],dtype='float'),0.0],GlyOPN=np.array([1.0],dtype='float'),GlyIBN=np.array([0.0],dtype='float')):
    threadLock.acquire()
    self.Neuron.NextStep(Glu, GlyOPN, GlyIBN)
    threadLock.release()

  def getOutput(self):
    return self.Neuron.getOutput()

if __name__ == '__main__':
  Ts=np.array( [0.005] , dtype=float)

  threadLock = threading.Lock()
  EBN=[]
  for ii in np.arange(0,10):
      EBN.append(EBNMCPU(ii,Ts,OnDir=0.0))

  for tc in EBN:
    tc.start() 

  for ii in np.arange(0,NSample):
    for tc in EBN:
      tc.run([np.array([AllY[ii,1]]),0.0],np.array([AllY[ii,2]]),np.array([AllY[ii,3]]))

    for tc in EBN:
      tc.join()

The problem is that I do not see any parallel activity in my system manager... 问题是我的系统管理器中没有看到任何并行活动...

Thank you for your comments/help, 感谢您的评论/帮助,

Pierre 皮埃尔

The problem is that I do not see any parallel activity in my system manager 问题是我的系统管理器中没有看到任何并行活动

That's because Python threads do not distribute over multiple CPUs/cores due to the global interpreter lock . 这是因为由于全局解释器锁, Python线程不会分布在多个CPU /内核上。 Use multiprocessing or joblib to write parallel Python programs. 使用multiprocessingjoblib编写并行的Python程序。

You're calling run() directly, which run the code in the same thread. 您直接调用run() ,它在同一线程中运行代码。 run() must have no parameter. run()必须没有参数。 You should pass every argument when constructing the object then call start() to run it in a new thread. 构造对象时,应传递每个参数,然后调用start()在新线程中运行它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM