Skip to content Skip to sidebar Skip to footer

Python Threading Not Processed Parallel

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 ide

Solution 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

Post a Comment for "Python Threading Not Processed Parallel"