为了解决多线程竞争资源的问题,threading提供了一个local()函数,该函数返回一个线程局部变量,实际上就是为每一个使用该变量的线程都提供一个变量的副本
import threading
from concurrent.futures import ThreadPoolExecutor
# 定义线程局部变量
mydata = threading.local()
# 定义准备作为线程执行体使用的函数
def action (max):
for i in range(max):
try:
mydata.x += i
except:
mydata.x = i
# 访问mydata的x的值
print('%s mydata.x的值为: %d' %
(threading.current_thread().name, mydata.x))
# 使用线程池启动两个子线程
with ThreadPoolExecutor(max_workers=2) as pool:
pool.submit(action , 10)
pool.submit(action , 10)
线程局部变量从另一个角度来解决多线程的并发访问问题,但并不能替代同步机制,两者解决的问题不同,同步机制是为了同步多个线程对共享资源的并发访问,是多个线程之间进行通信的有效方式,线程局部变量是为了隔离多个线程的数据共享,从根本上避免多个线程之间对共享资源(变量)的竞争,因此如果多个线程之间需要共享资源,以实现线程通信,则使用同步机制,如果仅仅许愿哦隔离多个线程之间的共享冲突,则使用局部变量
Thread类提供了一个Timer子类,该子类可用于控制指定函数在特定时间内执行一次
from threading import Timer
def hello():
print("hello, world")
# 指定10秒后执行hello函数
t = Timer(10.0, hello)
t.start()
from threading import Timer
import time
# 定义总共输出几次的计数器
count = 0
def print_time():
print("当前时间:%s" % time.ctime())
global t, count
count += 1
# 如果count小于10,开始下一次调度
if count < 10:
t = Timer(1, print_time)
t.start()
# 指定1秒后执行print_time函数
t = Timer(1, print_time)
t.start()
如果程序想取消Timer的调度,则可调用Timer对象的cancel()函数
如果要执行更复杂的任务调度,可以使用Python提供的sched模块,该模块提供了sched.schedule类,它就是任务调度器
sched.scheduler(timefunc=time.monotonic, delayfunc=time.sleep)构造器接受两个参数
import sched, time
import threading
# 定义线程调度器
s = sched.scheduler()
# 定义被调度的函数
def print_time(name='default'):
print("%s 的时间: %s" % (name, time.ctime()))
print('主线程:', time.ctime())
# 指定10秒之后执行print_time函数
s.enter(10, 1, print_time)
# 指定5秒之后执行print_time函数,优先级为2
s.enter(5, 2, print_time, argument=('位置参数',))
# 指定5秒之后执行print_time函数,优先级为1
s.enter(5, 1, print_time, kwargs={'name': '关键字参数'})
# 执行调度的任务
s.run()
print('主线程:', time.ctime())
执行结果为
C:\Users\davieyang\Downloads\codes\14\14.8>python sched_test.py
主线程: Wed Apr 29 01:22:27 2020
关键字参数 的时间: Wed Apr 29 01:22:32 2020
位置参数 的时间: Wed Apr 29 01:22:32 2020
default 的时间: Wed Apr 29 01:22:37 2020
主线程: Wed Apr 29 01:22:37 2020
文章来源互联网,如有侵权,请联系管理员删除。邮箱:417803890@qq.com / QQ:417803890
Python Free
邮箱:417803890@qq.com
QQ:417803890
皖ICP备19001818号-4
© 2019 copyright www.pythonf.cn - All rights reserved
微信扫一扫关注公众号:
Python Free