search

Home  >  Q&A  >  body text

关于下列python多线程代码输出效果的疑问?

下面代码是《python核心编程》关于多线程编程一章中的一个例子:

#!/usr/bin/env python

import threading
from time import sleep, ctime

loops = [ 4, 2 ]

class MyThread(threading.Thread):
    def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args

    def run(self):
        apply(self.func, self.args)

def loop(nloop, nsec):
    print 'start loop', nloop, 'at:', ctime()
    sleep(nsec)
    print 'loop', nloop, 'done at:', ctime()

def main():
    print 'starting at:', ctime()
    threads = []
    nloops = range(len(loops))

    for i in nloops:
        t = MyThread(loop, (i, loops[i]),
        loop.__name__)
        threads.append(t)

    for i in nloops:
        threads[i].start()

    for i in nloops:
        threads[i].join()

    print 'all DONE at:', ctime()

if __name__ == '__main__':
    main()

书上显示的输出结果是这样的

我自己打了一遍,输出结果是这样的

可以看到,我的loop0和loop1的显示内容混合到一起了,这样是对的吗?为什么会这样?

PHP中文网PHP中文网2889 days ago447

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-04-18 09:19:00

    You need to lock it here. The standard output is a shared resource. Everyone can write to the screen at the same time, so it may be confusing.
    You need to add a mutex lock here to tell other threads that I want to write now, so don’t write it yet. Then when you finish writing, tell other threads that I have finished writing, and you can apply to write.

    The

    loop function is written as:

    import threading
    #创建锁
    mutex = threading.Lock()
    
    def loop(nloop, nsec):
        #锁定
        mutex.acquire()
        print 'start loop', nloop, 'at:', ctime()
        sleep(nsec)
        print 'loop', nloop, 'done at:', ctime()
        #释放
        mutex.release()
        

    All codes are:

    #!/usr/bin/env python
    # encoding: utf-8
    
    
    import threading
    from time import sleep, ctime
    
    loops = [ 4, 2 ]
    
    class MyThread(threading.Thread):
        def __init__(self, func, args, name=''):
            threading.Thread.__init__(self)
            self.name = name
            self.func = func
            self.args = args
    
        def run(self):
            apply(self.func, self.args)
    
    # 创建锁
    mutex = threading.Lock()
    
    def loop(nloop, nsec):
        # 锁定
        mutex.acquire()
        print 'start loop', nloop, 'at:', ctime()
        sleep(nsec)
        print 'loop', nloop, 'done at:', ctime()
        # 释放
        mutex.release()
    
    def main():
        print 'starting at:', ctime()
        threads = []
        nloops = range(len(loops))
    
        for i in nloops:
            t = MyThread(loop, (i, loops[i]),
            loop.__name__)
            threads.append(t)
    
        for i in nloops:
            threads[i].start()
    
        for i in nloops:
            threads[i].join()
    
        print 'all DONE at:', ctime()
    
    if __name__ == '__main__':
        main()
    

    reply
    0
  • PHPz

    PHPz2017-04-18 09:19:00

    Three knowledge points are involved here

    1. Python thread scheduling strategy
      Python threads are actually native threads supported by the operating system. Python's multi-threading mechanism is based on the native thread mechanism of the operating system. Different operating systems have different implementations

    2. window/linux python thread scheduling strategy
      Search for "window thread scheduling strategy" or "linux thread scheduling strategy"

    3. python GIL lock - PYTHON single process without parallelism

    Then you will understand

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 09:19:00

    You can understand after running it a few times

    reply
    0
  • Cancelreply