Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

threads not running parallel in python script

I am new to python and threading. I am trying to run multiple threads at a time. Here is my basic code :

  import threading
  import time
  threads = []

  print "hello"

  class myThread(threading.Thread):
          def __init__(self,i):
                  threading.Thread.__init__(self)
                  print "i = ",i
                  for j in range(0,i):
                          print "j = ",j
                          time.sleep(5)

  for i in range(1,4):
          thread = myThread(i)
          thread.start()

While 1 thread is waiting for time.sleep(5) i want another thread to start. In short, all the threads should run parallel.

like image 638
Utkarsh Patel Avatar asked Oct 26 '25 14:10

Utkarsh Patel


1 Answers

You might have some misunderstandings on how to subclass threading.Thread, first of all __init__() method is roughly what represents a constructor in Python, basically it'll get executed every time you create an instance, so in your case when thread = myThread(i) executes, it'll block till the end of __init__().

Then you should move your activity into run(), so that when start() is called, the thread will start to run. For example:

import threading
import time
threads = []

print "hello"

class myThread(threading.Thread):
    def __init__(self, i):
        threading.Thread.__init__(self)
        self.i = i

    def run(self):
        print "i = ", self.i
        for j in range(0, self.i):
            print "j = ",j
            time.sleep(5)

for i in range(1,4):
    thread = myThread(i)
    thread.start()

P.S. Because of the existence of GIL in CPython, you might not be able to fully take advantages of all your processors if the task is CPU-bound.

like image 137
Shane Avatar answered Oct 28 '25 02:10

Shane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!