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 sequentially (i.e. thread2 starts after thread 1 ends, they don't both start at the same time). I wrote a simple script to test this, and that too runs threads sequentially.
import threading
def something():
for i in xrange(10):
print "Hello"
def my_thing():
for i in xrange(10):
print "world"
threading.Thread(target=something).start()
threading.Thread(target=my_thing).start()
Here's the output I get from running it:
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
world
world
world
world
world
world
world
world
world
world
The same behavior is observed with much larger number of iterations of the loops.
I tried searching the web and older SO answers, but I couldn't find anything that helped. Can someone please point out what is wrong with this code?
An initial thread executes sequentially, as if the code encountered is part of an implicit task region, called an initial task region, that is generated by the implicit parallel region surrounding the whole program.
A thread is a sequence of instructions that are being executed within the context of a process. One process can spawn multiple threads but all of them will be sharing the same memory.
This means that in python only one thread will be executed at a time. By only allowing a single thread to be used every time we run a Python process, this ensures that only one thread can access a particular resource at a time and it also prevents the use of objects and bytecodes at once.
Currently in python, threads get changed after executing some specified amount of bytecode instructions. They don't run at the same time. You will only have threads executing in parallel when one of them calls some I/O-intensive or not python-affecting module that can release GIL (global interpreter lock).
I'm pretty sure you will get the output mixed up if you bump the number of loops to something like 10000. Remember that simply spawning the second thread also takes "a lot" of time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With