Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

python - threading appears to run threads sequentially

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...