0

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?

1
  • You might want to know, that there is a huge difference between a true [PARALLEL] and just [CONCURRENT] code-execution models. Threads, not speaking about GIL-issues, do not provide a warranty of [PARALLEL] execution, but may help organise a [CONCURRENT] type of processing. Commented Jan 7, 2016 at 6:50

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

0

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

1 Comment

What does the Timer do? Where is the Spawn function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.