Python多线程_thread模块详解
_thread 模块的函数如下:
下面的示例是创建一个类,内含 5 个函数,每执行一个函数就激活一个线程,本示例同时执行 5 个线程。

图1:程序运行结果
声明:《Python系列教程》为本站“54笨鸟”官方原创,由国家机构和地方版权局所签发的权威证书所保护。
1) _thread.allocate_lock()
创建并返回一个 lckobj 对象。lckobj 对象有以下三个方法:- lckobj.acquire([flag]):用来捕获一个 lock。
- lcjobj.release():释放 lock。
- lckobj.locked():若对象成功锁定,则返回 True;否则返回 False。
2) _thread.exit()
拋出一个 SystemExit,以终止线程的执行。它与 sys.exit() 函数相同。3) _thread.get_ident()
读取目前线程的识别码。4) _thread.start_new_thread(func, args [, kwargs])
开始一个新的线程。下面的示例是创建一个类,内含 5 个函数,每执行一个函数就激活一个线程,本示例同时执行 5 个线程。
#创建多个线程 import _thread, time class threadClass : def __init__(self) : self. _threadFunc = { } self. _threadFunc['1'] = self.threadFunc1 self. _threadFunc['2'] = self.threadFunc2 self. _threadFunc['3'] = self.threadFunc3 self. _threadFunc['4'] = self.threadFunc4 def threadFunc(self, selection, seconds): self._threadFunc[selection] (seconds) def threadFunc1 (self, seconds) : _thread.start_new_thread(self.output, (seconds, 1) ) def threadFunc2 (self, seconds) : _thread.start_new_thread (self.output,(seconds, 2) ) def threadFunc3 (self, seconds) : _thread.start_new_thread (self.output, (seconds,3) ) def threadFunc4 (self, seconds) : _thread.start_new_thread(self.output, (seconds, 4) ) def output (self, seconds, number) : for i in range (seconds) : time. sleep(0.0001) print ("进程:d 已经运行"%number) mythread = threadClass () mythread.threadFunc('1', 800) mythread.threadFunc('2',700) mythread.threadFunc('3', 500) mythread.threadFunc('4',300) time. sleep(5.0)保存运行程序,结果如下所示:

图1:程序运行结果
声明:《Python系列教程》为本站“54笨鸟”官方原创,由国家机构和地方版权局所签发的权威证书所保护。