Python threading not being processed in parallel

I am an intermediate bee for python and would like to run the same examples of multiple instances in parallel to collect data and make decisions for the financial market. To continue my idea, I run the following code to see how python works, it seems to work with one full run of an instance of the first class, and after the instances of the second class I would like to execute this in parallel, how can I ...? The following is 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 indicated 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)> 
+5
source share
1 answer

The problem is here:

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

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

Instead, you want something like this:

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

Note that there are no brackets after run

Here's the full program with the proposed 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 the 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 
+8
source

Source: https://habr.com/ru/post/1269848/


All Articles