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单例模式的多种实现方法

前言 单例模式(Singleton Pattern),是一种软件设计模式,是类只能实例化一个对象, 目的是便于外界的访问,节约系统资源,如果希望系统中 只有一个对象可以访问,就用单例模式...

Python编写生成验证码的脚本的教程

在web开发中经常用到验证码,为了防止机器人注册或者恶意登陆和查询等,作用不容小觑 但是验证码其实不是一个函数就能搞定的,它需要生成图片和水印,其实每种语言都有相关的函数生成图片和文字水...

python实现逆波兰计算表达式实例详解

本文实例讲述了python实现逆波兰计算表达式的方法。分享给大家供大家参考。具体分析如下: 逆波兰表达式又叫做后缀表达式。在通常的表达式中,二元运算符总是置于与之相关的两个运算对象之间,...

在Python中操作文件之read()方法的使用教程

 read()方法读取文件size个字节大小。如果读取命中获得EOF大小字节之前,那么它只能读取可用的字节。 语法 以下是read()方法的语法: fileObject.r...

Python字符串处理之count()方法的使用

 count()方法返回出现在范围内串子数range [start, end]。可选参数的start和end都解释为片符号。 语法 以下是count()方法的语法: str...