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

关于下列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的显示内容混合到一起了,这样是对的吗?为什么会这样?


你可以多运行几次就明白了


这里需要加锁,标准输出是共享资源,大家都可以同时向屏幕写东西,所以可能混乱。
这里需要加入互斥锁,告诉别的线程,我现在要写,你们先别写,然后写完了告诉别的线程,我写完了,你们可以申请写了。

loop 函数写成:

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

所有代码为:

#!/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()

这里涉及3个知识点

  1. python 线程调度策略
    python的线程实际就是操作系统所支持的原生线程,python的多线程机制建立在操作系统的原生线程机制之上,不同的操作系统有不同的实现

  2. window/linux python 线程调度策略
    搜索 “window 线程调度策略” or "linux 线程调度策略"

  3. python GIL 锁 —— PYTHON单进程无并行

然后你就懂了

【热门文章】
【热门文章】