Index ¦ Archives ¦ Atom

Python多线程


多线程类相当于同时执行多个不同程序,多线程运行有如下有点: 使用线程可以把占据长时间的程序中的任务放到后台处理,可以弹出一个进度条来显示处理进度. 能提高程序的运行速度. * 在一些需要等待的任务实现上线程就体现出优势了,比如等待用户输入,文件读写和网络数据收发等.在这种情况下可以释放内存等珍贵资源.

线程在执行过程中与进程还是有区别的.每个独立的线程有一个程序运行入口,顺序执行序列和程序的出口.但是线程不能独立执行,必须依存在应用程序中,由应用程序提供多个线程执行控制.
每个线程都有自己的一组cpu寄存器,称为线程的上下文,该上下文反映了线程上次运行该线程的cpu寄存器的状态.
指令指针和堆栈指针寄存器是线程上下文中两个最重要的寄存器.线程总是在进程得到上下文中运行的,这些地址都用于标志拥有线程的进程地址空间中的内存.
* 线程可以被抢占(终端) * 在其他线程正在运行时,线程可以暂时搁置(睡眠),这就是线程的退让.


学习python线程

Python中使用线程有两种方式: 1. 函数 2. 用类包装的线程对象

thread.start_new_thread(function,args[, kwargs])
参数说明:
* function:线程函数 * args:传递给线程的参数,它必须是个tuple类型. * kwargs:可选参数

示例如下:

# -*- coding: utf-8 -*-

import thread,time

def print_time(threadname,delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print "%s: %s" % (threadname,time.ctime(time.time()))

#创建两个线程
try:
    thread.start_new_thread(print_time,("Thread-1",2,))
    thread.start_new_thread(print_time,("Thread-2",4,))
except:
    print "Error: unable to start thread"

while 1:
    pass

示例结果为:

ivesein@ivesein-UbuntuPC:~$ python pt.py 
Thread-1: Tue Jun 14 21:22:58 2016
Thread-2: Tue Jun 14 21:23:00 2016
Thread-1: Tue Jun 14 21:23:00 2016
Thread-1: Tue Jun 14 21:23:02 2016
Thread-2: Tue Jun 14 21:23:04 2016
Thread-1: Tue Jun 14 21:23:04 2016
Thread-1: Tue Jun 14 21:23:06 2016
Thread-2: Tue Jun 14 21:23:08 2016
Thread-2: Tue Jun 14 21:23:12 2016
Thread-2: Tue Jun 14 21:23:16 2016

线程的结束一般依靠线程函数的自然结束;也可以在线程函数中调用thread.exit()函数,抛出SystemExit exception信息,达到退出线程的目的.


线程模块

Python通过两个标准库thread和threading提供对线程的支持.thread提供了低级别,原始的线程,以及一个简单的线程锁.

thread提供以下方法:
* threading.currentThread():返回当前的线程变量.
* threading.enumerate():返回一个包含正在运行的线程list.正在运行指线程启动后,结束前.不包括启动前和终止后的线程.
* threading.activeCount():返回正在运行的线程数量,与len(threading,enumberate())有相同结果
线程模块还提供了Thread类来处理线程.
Thread类提供了以下方法:
* run():用以表示线程活动的方法.
* start():启动线程活动.
* join([time]):等待至线程中止.这阻塞调用线程直至线程的join()方法被调用中止-正常退出或者抛出未处理异常或者可选的超时发生.
* isAlive():返回线程是否活动.
* getName():返回线程名.
* setName():设置线程名.

使用threading模块创建线程

使用threading模块创建线程,直接从threading.Thread继承,然后重写_init_()方法和run()方法:

# -*- coding: utf-8 -*-

import threading,time

exitFlag = 0

class myThread(threading.Thread):           # 继承父类threading.Thread
    def __init__(self,threadID,name,counter):
        threading.Thread.__init__(self)
        self.threadID = threarID
        self.name = name
        self.counter = counter
    def run(self):
        print "Starting " + self.name
        print_time(self.name, self.counter, 5)
        print "Exiting " + self.name

    def print_time(threadname, delay, counter):
        while counter:
            if exitFlag:
                thread.exit()
            time.sleep(delay)
            print "%s: %s" % (threadname, time.ctime(time.time()))
            counter -= 1

#创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

#开启线程
thread1.start()
thread2.start()

print "Exiting Main Thread"

后面将更进一步学习threading.Thread模块

© Ivesein. Built using Pelican. Theme by Giulio Fidente on github.