文档详情

pythonthread(Python多线程处理)2.docx

发布:2017-06-06约5.89千字共6页下载文档
文本预览下载声明
Python 多线程Python中使用线程有两种方式:函数或者用类来包装线程对象。函数式:调用thread模块中的start_new_thread()函数来产生新线程。语法如下:thread.start_new_thread( function, args[, kwargs] )参数说明:function - 线程函数。args - 传递给线程函数的参数,他必须是个tuple类型。kwargs - 可选参数。#coding=utf-8#!/usr/bin/pythonimport threadimport time# 为线程定义一个函数defprint_time( threadName, delay):count = 0while count 5:time.sleep(delay)count += 1print %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 threadwhile 1:pass执行以上程序输出结果如下:Thread-1: Thu Jan 22 15:42:17 2009Thread-1: Thu Jan 22 15:42:19 2009Thread-2: Thu Jan 22 15:42:19 2009Thread-1: Thu Jan 22 15:42:21 2009Thread-2: Thu Jan 22 15:42:23 2009Thread-1: Thu Jan 22 15:42:23 2009Thread-1: Thu Jan 22 15:42:25 2009Thread-2: Thu Jan 22 15:42:27 2009Thread-2: Thu Jan 22 15:42:31 2009Thread-2: Thu Jan 22 15:42:35 2009线程的结束一般依靠线程函数的自然结束;也可以在线程函数中调用thread.exit(),他抛出SystemExit exception,达到退出线程的目的。Python通过两个标准库thread和threading提供对线程的支持。thread提供了低级别的、原始的线程以及一个简单的锁。thread 模块提供的其他方法:threading.currentThread(): 返回当前的线程变量。threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。除了使用方法外,线程模块同样提供了Thread类来处理线程,Thread类提供了以下方法:run():?用以表示线程活动的方法。start():启动线程活动。join([time]):?等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。isAlive():?返回线程是否活动的。getName():?返回线程名。setName():?设置线程名。使用Threading模块创建线程使用Threading模块创建线程,直接从threading.Thread继承,然后重写__init__方法和run方法:#coding=utf-8#!/usr/bin/pythonimport threadingimport timeexitFlag = 0class myThread (threading.Thread): #继承父类threading.Threaddef __init__(self, threadID, name, counter): threading.Thread.__init__(self)self.threadID = threadID self.name = nameself.counter = counterdef run(self): #把要执行的代码写到run函数里面线程在创建后会直接运行run函数print Starting + self.nameprint_time(self.name, self.counter, 5)print Exiting + self.namedefprint_time(thr
显示全部
相似文档