threading appears to run threads sequentially

后端 未结 4 1409
醉话见心
醉话见心 2020-12-03 17:30

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

4条回答
  •  广开言路
    2020-12-03 18:21

    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
    

提交回复
热议问题