什么是线程模块
python通过两个标准库thread和threading提供对线程的支持。thread提供了低级别的、原始的线程以及一个简单的锁。
threading 模块提供的其他方法:
1.threading.currentthread(): 返回当前的线程变量。
2.threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
3.threading.activecount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。
除了使用方法外,线程模块同样提供了thread类来处理线程,thread类提供了以下方法:
1.run(): 用以表示线程活动的方法。
2.start():启动线程活动。
3.join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
4.isalive(): 返回线程是否活动的。
5.getname(): 返回线程名。
6.setname(): 设置线程名。
使用使threading模块创建线程
使用threading模块创建线程,直接从threading.thread继承,然后重写__init__方法和run方法:
# !/usr/bin/python# -*- coding: utf-8 -*-import threadingimport timeexitflag = 0class mythread(threading.thread): # 继承父类threading.thread def __init__(self, threadid, name, counter): threading.thread.__init__(self) self.threadid = threadid self.name = name self.counter = counter def run(self): # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数 print "starting " + self.name print_time(self.name, self.counter, 5) print "exiting " + self.namedef print_time(threadname, delay, counter): while counter: if exitflag: (threading.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"
以上程序执行结果如下:
starting thread-1starting thread-2exiting main threadthread-1: thu mar 21 09:10:03 2013thread-1: thu mar 21 09:10:04 2013thread-2: thu mar 21 09:10:04 2013thread-1: thu mar 21 09:10:05 2013thread-1: thu mar 21 09:10:06 2013thread-2: thu mar 21 09:10:06 2013thread-1: thu mar 21 09:10:07 2013exiting thread-1thread-2: thu mar 21 09:10:08 2013thread-2: thu mar 21 09:10:10 2013thread-2: thu mar 21 09:10:12 2013exiting thread-2
以上就是本篇文章所讲述的所有内容,这篇文章主要介绍了python线程模块的相关知识,希望你能借助资料从而理解上述所说的内容。希望我在这片文章所讲述的内容能够对你有所帮助,让你学习python更加轻松。
更多相关知识,请访问python教程栏目。
以上就是什么是python线程模块?九种方法助你了解线程模块的详细内容。
