线程允许多个任务同时运行。例如,当任务A正在运行时,我不必等待它完成。同时,任务B、C也会运行。当任务同时运行时,它们需要多个CPU。
为了并发地运行线程,Python使用了一种被称为任务切换的技术。结果是,Python在每个任务之间快速切换。使得它看起来像是多个任务在并行运行,使得它在事件驱动的任务中很有用。线程是轻量级的,它需要更少的内存,从而节省CPU资源。
一个线程有一个入口,一个执行点和一个退出点。Python库包含一个定时器,它是**"线程 "**类的一个子类,用于在限定的时间内执行代码。
Python中的线程 Timer()在定义为参数的延迟后开始。因此,定时器类调用自己,使下面的操作延迟执行,延迟的时间与指定的时间相同。
要想继续学习,读者需要具备以下条件。
每隔指定的秒数后,就会调用一个定时器类的函数。start()是一个用于初始化定时器的函数。要结束或退出定时器,必须使用cancel()函数。为了使用线程类,导入线程类是必要的。使用函数time.sleep(secs)可以使调用的线程暂停数秒。
py 代码解读复制代码## How class threading.Timer() in python works
import threading as th
## Defining a method
def sctn():
print("SECTION FOR LIFE \n")
S = th.Timer(5.0, sctn)
S.start()
print("Exit Program\n")
SECTION FOR LIFE
。在第二个例子中,我将向你展示如何实现暂停方法cancel()
,我们在前面已经看到它是为了结束一个线程。
py 代码解读复制代码##Illustrating the use of cancel() method in class Timer.
import threading as th
## Defining of a method
def sctn():
print("SECTION FOR LIFE \n")
S = th.Timer(5.0, sctn)
S.start()
print("PROGRAM TERMINATION\n")
S.cancel()
最新的线程模块包含在当前的Python 2.4中,与之前的线程模块相比,它对线程提供了更强大、更高级别的支持。
线程模块暴露了线程模块的所有方法,并提供了一些额外的功能,如下图所示。
bash 代码解读复制代码 thread.activeCount() − Returns how many thread objects are active.
thread.currentThread() − Returns how many thread objects in the caller's thread control.
thread.enumerate() − Returns an overview list of all thread objects that are currently active.
线程的美妙之处在于,你可以告诉计算机在其他时间执行一项任务,或者同时进行。你还可以在不同的线程上同时执行代码,这使它变得非常强大。一个定时器类总是以间隔方式运行。
Python Timer 类用于执行一个操作或在指定的时间段过后让一个函数运行。线程类有一个子类,叫做类Timer。从技术角度讲,当我们需要有时间限制的操作(方法)时,我们将创建Timer对象。
要使用Timer类,我们首先要导入时间模块。args参数总是最好用来声明要调用的函数的参数。
py 代码解读复制代码##Timers
##Execute code at timed intervals
##Imports and Displays
import time
from threading import Timer
def display(msg):
print(msg + ' ' + time.strftime('%H:%M:%S'))
##Basic timer
def run_once():
display('run_once:')
t=Timer(10,display,['Timeout:'])
t.start()#Here run is called
run_once()
##Runs immediately and once
print('Waiting.....')
##Lets make our timer run in intervals
##Put it into a class
##Making it run until we stop it
##Just getting crazy.Notice We have multiple timers at once!
class RepeatTimer(Timer):
def run(self):
while not self.finished.wait(self.interval):
self.function(*self.args,**self.kwargs)
print(' ')
##We are now creating a thread timer and controling it
timer = RepeatTimer(1,display,['Repeating'])
timer.start() #recalling run
print('Threading started')
time.sleep(10)#It gets suspended for the given number of seconds
print('Threading finishing')
timer.cancel()
在使用Python装饰器工作时,将知道如何扩展Python Timer以使其被重复使用。使用装饰器的重要性在于,它只被实现一次,而函数每次都被计时。
py 代码解读复制代码import functools
import time
def timer(meth):
@functools.wraps(meth)
def timer_container(*args, **kwargs):
click = time.flow()
value: object = meth(*args, **kwargs)
clock = time.flow()
time_passed = click - clock ##getting the time spent
print(f"TIME PASSED IS: {time_passed:0.2f} SECS") ##displaying time passed to 2 decimal places
return value
return timer_container()
当代码运行时,输出应该是。
bash 代码解读复制代码TIME PASSED IS: 0.59 SECS
在这篇文章中,我们已经学到了以下内容。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。