python 多线程模块_Python多线程_thread模块详解

_thread 模块的函数如下:

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值