icecreamscoop
icecreamscoop

Reputation: 71

Python - Threads not parallel

I have my runner code that starts 5 threads, however, it only starts 1 thread (by which I know because it doesn't loop), take a look at the code:

import Handle
import threading

h = Handle.Handle()
h.StartConnection()
for i in range(0, 5):
    print("Looped")
    t = threading.Thread(target=h.Spawn())
    t.start()

It only prints "Looped" once and only runs "Spawn" once aswell. Any ideas?

Upvotes: 0

Views: 1390

Answers (3)

masnun
masnun

Reputation: 11906

The issues I noticed:

  • You are replacing the t variable in each loop. So finally you just have one thread assigned to it.
  • Does the Spawn function return a function? If it does then it's okay, otherwise you should just pass Spawn to the target, not call Spawn() .
  • If the Spawn function is long running in nature (I assume it is), then your call to the Spawn function will block the loop and wait until it returns. This is why your loop might print "looped" once and the Spawn function getting called just once too.

My suggestion would be like this:

import Handle
import threading

h = Handle.Handle()
h.StartConnection()

threads = []

for i in range(0, 5):
    print("Looped")
    t = threading.Thread(target=h.Spawn)
    threads.append(t)
    t.start()

I took a list to store the threads - the threads list. Then appending each of the thread in it before calling start. Now I can iterate over the threads list anytime I want (may be for joining them?).

Also since I assumed Spawn is a long running function, I passed it as the target to the Thread constructor. So it should be run in background when we call start on the thread. Now it should no longer block the loop.

Upvotes: 2

Narayan C.R
Narayan C.R

Reputation: 874

Try this code .

import Handle
import threading

h = Handle.Handle()
h.StartConnection()
for i in range(0, 5):
    print("Looped")
    threading.Timer(5.0, h).start()

Upvotes: 0

Daniel
Daniel

Reputation: 42748

You are not running threads, you run the Spawn-method right in the main thread. target needs to be a function, not the result of that function:

t = threading.Thread(target=h.Spawn)

Upvotes: 2

Related Questions