Python 官方文档:入门教程 => 点击学习
CPython implementation detail: 在 Cpython 中,由于存在全局解释器锁, 同一时刻只有一个线程可以执行 Python 代码(虽
CPython implementation detail: 在 Cpython 中,由于存在全局解释器锁, 同一时刻只有一个线程可以执行 Python 代码(虽然某些性能导向的库可能会去除此限制)。 如果你想让你的应用更好地利用多核心计算机的计算资源,推荐你使用multiprocessing或concurrent.futures.ProcessPoolExecutor但是,如果你想要同时运行多个 I/O 密集型任务,则多线程仍然是一个合适的模型。
再来引入一个概念:
可以知道python线程是并发的。
关于线程Threading的方法(获取线程的某种属性)。
线程简介:
Thread类表示在单独的控制线程中运行的活动。指定活动有两种方法:将可调用对象传递给构造函数,或重写子类中的run()方法。子类中不应重写任何其他方法(构造函数除外)。换句话说,只重写这个类的_init__;()和run()方法
一旦线程活动开始,该线程会被认为是 '存活的' 。当它的run() 方法终结了(不管是正常的还是抛出未被处理的异常),就不是'存活的'。
先看看该类的参数有哪些:
class threading.
Thread
(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
为了便于理解,先举一个小例子,为了方便理解,先简单了解一下该类的一个方法(函数在类中被称为方法):
import threading
import time
# 打印函数a
def printa(a):
count = 0
while count < 5:
time.sleep(2)
print("线程:%s。打印:%s。时间:%s。" % (threading.current_thread().name, a, time.ctime()))
count += 1
# 打印函数b
def printb(b):
count = 0
while count < 5:
time.sleep(4)
print("线程:%s。打印:%s。时间:%s。" % (threading.current_thread().name, b, time.ctime()))
count += 1
# threading.Thread(target=,args=(),name='')
t1 = threading.Thread(target=printa, args=(10,), name='线程1')
t2 = threading.Thread(target=printb, args=(20,), name='线程2')
t1.start()
t2.start()
t1.join()
t2.join()
print("退出主线程")
import threading
import time
# 打印函数a
def printa(a):
count = 0
while count < 5:
time.sleep(2)
print("线程:%s。打印:%s。时间:%s。" % (threading.current_thread().name, a, time.ctime()))
count += 1
# threading.Thread(target=,args=(),name='')
threadList = []
for i in range(3):
t = threading.Thread(target=printa, args=(i,))
threadList.append(t)
for t in threadList:
t.start()
for t in threadList:
t.join()
print("退出主线程")
到此这篇关于python 多线程threading程序详情的文章就介绍到这了,更多相关python 多线程threading内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: python 多线程threading程序详情
本文链接: https://www.lsjlt.com/news/117338.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0