Python多线程编程(二):启动线程的两种方法

yipeiwu_com5年前Python基础

在Python中我们主要是通过thread和threading这两个模块来实现的,其中Python的threading模块是对thread做了一些包装的,可以更加方便的被使用,所以我们使用threading模块实现多线程编程。一般来说,使用线程有两种模式,一种是创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行;另一种是直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的 class里。

将函数传递进Thread对象

复制代码 代码如下:

''' 
Created on 2012-9-5 
 
@author:  walfred
@module: thread.ThreadTest1 
@description:
'''   
import threading 
 
def thread_fun(num): 
    for n in range(0, int(num)): 
        print " I come from %s, num: %s" %( threading.currentThread().getName(), n) 
 
def main(thread_num): 
    thread_list = list(); 
    # 先创建线程对象 
    for i in range(0, thread_num): 
        thread_name = "thread_%s" %i 
        thread_list.append(threading.Thread(target = thread_fun, name = thread_name, args = (20,))) 
 
    # 启动所有线程    
    for thread in thread_list: 
        thread.start() 
 
    # 主线程中等待所有子线程退出 
    for thread in thread_list: 
        thread.join() 
 
if __name__ == "__main__": 
    main(3)

程序启动了3个线程,并且打印了每一个线程的线程名字,这个比较简单吧,处理重复任务就派出用场了,下面介绍使用继承threading的方式;

继承自threading.Thread类

复制代码 代码如下:

'''
Created on 2012-9-6
 
@author: walfred
@module: thread.ThreadTest2
''' 
 
import threading 
 
class MyThread(threading.Thread): 
    def __init__(self): 
        threading.Thread.__init__(self); 
 
    def run(self): 
        print "I am %s" %self.name 
 
if __name__ == "__main__": 
    for thread in range(0, 5): 
        t = MyThread() 
        t.start()

接下来的文章,将会介绍如何控制这些线程,包括子线程的退出,子线程是否存活及将子线程设置为守护线程(Daemon)。

相关文章

Python编程中对super函数的正确理解和用法解析

当在子类需要调用父类的方法时,在python2.2之前,直接用类名调用类的方法,即非绑定的类方法,并把自身对象self作参数传进去。 class A(object): def...

Python的Tkinter点击按钮触发事件的例子

Python的Tkinter点击按钮触发事件的例子

如果要开发一个比较大的程序,那么应该先把代码封装起来,在面向对象编程中,就是封装成类 先看代码: import tkinter as tk class App: def __in...

手把手教你使用Python创建微信机器人

手把手教你使用Python创建微信机器人

微信,一个日活10亿的超级app,不仅在国内社交独领风骚,在国外社交也同样占有一席之地,今天我们要将便是如何用Python来生成一个微信机器人,突然想起鲁迅先生曾经说过的一句话:...

从零学Python之入门(三)序列

sequence 序列 sequence(序列)是一组有顺序的元素的集合 (严格的说,是对象的集合,但鉴于我们还没有引入“对象”概念,暂时说元素) 序列可以包含一个或多个元素,也可以没有...

Python实现通过解析域名获取ip地址的方法分析

Python实现通过解析域名获取ip地址的方法分析

本文实例讲述了Python实现通过解析域名获取ip地址的方法。分享给大家供大家参考,具体如下: 从网上查找的一些资料,特此做个笔记 案例1: def getIP(domain):...