I am trying to use threads in a Python project I am working on, but threads don\'t appear to be behaving as they are supposed to in my code. It seems that all threads run se
In the time it takes the second thread to start the first thread loops and prints already.
Here it looks like this, you can see the 2nd thread starting after the first emitted a few hellos.
Hello
Hello
Hello
Hello
Hello
Helloworld
Helloworld
Helloworld
Helloworld
Helloworld
world
world
world
world
world
Btw: Your example is not meaningful at all. The only reason for Threads is IO, and IO is slow. When you add some sleeping to simulate IO it should work as expected:
import threading
from time import sleep
def something():
for i in xrange(10):
sleep(0.01)
print "Hello"
def my_thing():
for i in xrange(10):
sleep(0.01)
print "world"
threading.Thread(target=something).start()
threading.Thread(target=my_thing).start()
a wild mix appears:
worldHello
Helloworld
Helloworld
worldHello
Helloworld
Helloworld
worldHello
Helloworld
worldHello
Helloworld