线程似乎可以按顺序运行线程 [英] threading appears to run threads sequentially

查看:82
本文介绍了线程似乎可以按顺序运行线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我正在处理的Python项目中使用线程,但是线程似乎并没有像我的代码中所预期的那样工作.似乎所有线程都按顺序运行(即线程2在线程1结束后开始,它们不是同时启动).我编写了一个简单的脚本来对此进行测试,并且该脚本也按顺序运行线程.

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.

我尝试搜索网络和较旧的SO答案,但找不到任何有帮助的方法. 有人可以指出这段代码有什么问题吗?

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?

推荐答案

当前在python中,执行一定数量的字节码指令后,线程会发生变化.它们不会同时运行.当线程中的一个调用某些I/O密集型或不影响python的模块(这些模块可以释放GIL(全局解释器锁))时,您将只有并行执行的线程.

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

我敢肯定,如果将循环数增加到10000之类的话,您将得到混合的输出.请记住,仅产生第二个线程也需要很多"时间.

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.

这篇关于线程似乎可以按顺序运行线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆