首页 > 编程笔记

Python多线程_thread模块详解

_thread 模块的函数如下:

1) _thread.allocate_lock()

创建并返回一个 lckobj 对象。lckobj 对象有以下三个方法:

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:程序运行结果

优秀文章