Python多线程编程(一)

来源:互联网 发布:礼品卡兑换系统源码 编辑:程序博客网 时间:2024/04/30 10:24

1. threading模块

Python 实现多线程编程可以通过thread模块(thread模块在Python3中更名为_thread)或者是更高级的threading模块,这里主要讲的是threading模块。

1.1 threading模块对象

  • Thread,表示一个线程的执行的对象
  • Lock,锁源语对象
  • Timer,与Thread类似,只是他要等待一段时间后才开始运行

1.2.1 threading.Thread 对象

  • Thread类表示在单独的一个控制线程中运行的一个活动。Thread类用两种指定活动的方法:一个是通过传递可调用对象给构造参数;另一个是在子类中覆盖run()方法——在子类中不应该覆盖其他方法。

threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

  • Thread类中的方法
    • start(),开始线程的执行
    • join(timeout=None),程序主线程挂起,直到子线程结束;如果给了timeout,则最多阻塞timeout秒
    • run(),定义线程的功能的函,run()方法一般是被子类重写使用的
    • getName(),返回线程的名字
    • setName(),设置线程的名字
    • isAlive()
    • setDaemon(daemonic),把线程的标志设为daemonic(一定要在调用start()函数之前调用)

1.2.2 例1——通过传递可调用对象给构造参数

#!/usr/local/bin python#coding: utf-8import threadingimport sysimport timeTHREAD_NUM = 3  #设置线程个数def worker():    for i in range(5):        print "Thread name is %s----current values is %d" % (threading.currentThread().getName(),i)        if ( i == 3 ):            #i的值为3时,当前线程会阻塞,转而执行其他的线程            time.sleep(4)        #print "Thread name is %s----current values is %d" % (threading.currentThread().getName(),i)def main():    threads = []    for i in range(THREAD_NUM):        thread = threading.Thread(target=worker,args=())        thread.start()      #启动线程        threads.append(thread)    for thread in threads:        thread.join()    #阻塞线程if __name__ == "__main__":    main()

输出结果

Thread name is Thread-1----current values is 0Thread name is Thread-1----current values is 1Thread name is Thread-1----current values is 2Thread name is Thread-1----current values is 3Thread name is Thread-2----current values is 0Thread name is Thread-2----current values is 1Thread name is Thread-2----current values is 2Thread name is Thread-2----current values is 3Thread name is Thread-3----current values is 0Thread name is Thread-3----current values is 1Thread name is Thread-3----current values is 2Thread name is Thread-3----current values is 3Thread name is Thread-1----current values is 4Thread name is Thread-2----current values is 4Thread name is Thread-3----current values is 4

1.2.3 例2———子类重写run()方法

#!/usr/local/bin python#coding: utf-8import threadingimport sysimport timeTHREAD_NUM = 3  #设置线程个数class MyThread(threading.Thread):    def __init__(self):        threading.Thread.__init__(self)    def run(self):        for i in range(5):            print "Thread name is %s----current values is %d" % (threading.currentThread().getName(),i)            if ( i == 3 ):                #i的值为3时,当前线程会阻塞,转而执行其他的线程                time.sleep(4)            #print "Thread name is %s----current values is %d" % (threading.currentThread().getName(),i)def main():    threads = []    for i in range(THREAD_NUM):        thread = MyThread()        thread.start()            threads.append(thread)    for thread in threads:        thread.join()if __name__ == "__main__":    main()

输出结果同上。

2. Python多线程编程的特点

由于全局解释器GIL的存在,一次只有一个线程可以执行代码,因此Python的多线程编程并不能充分的利用多核CPU的优势。但是具体问题具体分析。对于CPU密集型,可以使用Python的multiprocessing模块,即使用多进程;但是对于IO密集型的,多线程依然是个不错的选择。

0 0
原创粉丝点击