Python: 关于thread模块和threading模块的选择

最近在阅读Python核心编程(第二版)。
做者在多线程编程一章讲到thread和threading这两个模块时,
提到要避免使用thread模块,取而代之地使用threading模块。

以后点明了缘由——
"更高级别的threading模块更为先进,对线程支持更为完善,
并且使用thread模块里的属性有可能会与threading出现冲突。
其次,低级别的thread模块的同步原语不多(实际上只有一个),而threading模块则有不少。"

阅读完以后的整体感觉,就是threading更为全面和强大,应该多用threading模块,而不是thread模块。

同时也有一点疑问,当问题解决十分简单时(仅用thread模块就能够完成),
那么此时thread相比threading还有什么缺陷吗?
(面对简单问题时,我更倾向于使用thread,由于thread更为简单。)php

 

python的thread模块是比较底层的模块,python的threading模块是对thread作了一些包装的,能够更加方便的被使用。python

若是是简单应用,用thread可能更方便简单;但真正的业务系统确定不会简单了,因此仍是推荐threading。编程

通常来讲,使用线程有两种模式,一种是建立线程要执行的函数,把这个函数传递进Thread对象里,让它来执行;另外一种是直接从Thread继承,建立一个新的class,把线程执行的代码放到这个新的 class里。多线程

Python thread实现多线程app

#-*- encoding: gb2312 -*-
import string, threading, time

def thread_main(a):
    global count, mutex
    # 得到线程名
    threadname = threading.currentThread().getName()

    for x in xrange(0, int(a)):
        # 取得锁
        mutex.acquire()
        count = count + 1
        # 释放锁
        mutex.release()
        print threadname, x, count
        time.sleep(1)

def main(num):
    global count, mutex
    threads = []

    count = 1
    # 建立一个锁
    mutex = threading.Lock()
    # 先建立线程对象
    for x in xrange(0, num):
        threads.append(threading.Thread(target=thread_main, args=(10,)))
    # 启动全部线程
    for t in threads:
        t.start()
    # 主线程中等待全部子线程退出
    for t in threads:
        t.join()  


if __name__ == '__main__':
    num = 4
    # 建立4个线程
    main(4)

 

Python threading实现多线程函数

#-*- encoding: gb2312 -*-
import threading
import time

class Test(threading.Thread):
    def __init__(self, num):
        threading.Thread.__init__(self)
        self._run_num = num

    def run(self):
        global count, mutex
        threadname = threading.currentThread().getName()

        for x in xrange(0, int(self._run_num)):
            mutex.acquire()
            count = count + 1
            mutex.release()
            print threadname, x, count
            time.sleep(1)

if __name__ == '__main__':
    global count, mutex
    threads = []
    num = 4
    count = 1
    # 建立锁
    mutex = threading.Lock()
    # 建立线程对象
    for x in xrange(0, num):
        threads.append(Test(10))
    # 启动线程
    for t in threads:
        t.start()
    # 等待子线程结束
    for t in threads:
        t.join()
相关文章
相关标签/搜索