Python Threading not processed parallel

本秂侑毒 提交于 2021-02-04 07:11:24

问题


I'm intermidiate bee for python and would like to run the same class instances of few in parallel mode for fetching data and decision making for financial market. To proceed my idea, I run the following code to see how python works, it seems it works one complete run of first class instance and after second class instances, I would like to run this parallely, how can I...? Below is the some sample code for testing..

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())

and the results as below....

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)>

回答1:


The problem is here:

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

target= takes a callable object or None. F.run() executes F.run immediately, waits for it finish, and then passes the return value (which is None in your run() method) as the target.

You want something like this instead:

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

Note that there's no parentheses after run

Here's the complete program with the suggested change:

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()

And output (Python 3.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


来源:https://stackoverflow.com/questions/45113867/python-threading-not-processed-parallel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!