Python 全栈:Python 多线程和协程 6 方面使用逻辑通俗易懂总结

多线程铺垫

一般地,一个程序或者一个 App,默认只在一个进程的一个线程中执行,这个线程称为主线程。如果需要开启至少另外一个线程做任务,那么就要用到今天的知识——多线程,及高效的协程技术。

首先,导入线程相关的模块 threading:

In [41]: import threading

threading 的方法 current_thread() 返回当前线程:

In [42]: t = threading.current_thread()

In [43]: t
Out[43]: <_MainThread(MainThread, started 30484)>

所以,验证了程序默认是在 MainThead 中执行。

t.getName() 获得这个线程的名字;其他常用方法,getName() 获得线程 id,isAlive() 判断线程是否存活。

In [44]: t.getName()
Out[44]: 'MainThread'

In [45]: t.ident
Out[45]: 30484

In [46]: t.isAlive()
Out[46]: True

到目前为止,我们有且仅有一个“干活”的主线程,接下来开始创建自己的一个线程。

创建线程

创建一个线程:

In [47]: my_thread = threading.Thread()

创建一个名称为 my_thread 的线程:

my_thread = threading.Thread(name='my_thread')

创建线程,需要告诉这个线程,它能帮助我们做什么。“做什么”是通过参数 target 传入,参数类型为 callable。

In [49]: def print_i(i):
    ...:     print('打印i:%d'%(i,))

In [50]: my_thread = threading.Thread(target=print_i,args=(1,))

my_thread 线程已全副武装,但是,我们得按下发射按钮,启动 start(),它才开始真正起飞。

In [52]: my_thread.start()

打印结果如下,其中 args 指定函数 print_i 需要的参数 i,类型为元组。
打印i:1
至此,多线程相关的基本知识点,总结完毕。

但是,仅仅知道这些,还不够!接下来,聊聊多线程编程,最本质的一些东西。

交替获得 CPU 时间片

为了更好解释,假定计算机是单核的,尽管对于 CPython,这个假定有些多余。

开辟 3 个线程,装载到 threads 中:

In [1]: import time
In [3]: import threading

In [14]: def print_time():
    ...:     for _ in range(5): # 在每个线程中打印 5 次
    ...:         time.sleep(0.1) # 模拟打印前的相关处理逻辑
    ...:         print('当前线程%s,打印结束时间为:%s' %(threading.current_thread().getName(
    ...: ),time.time()))

In [7]: threads = [threading.Thread(name='t%d'%(i,),target=print_time) for i in range(3)]

启动 3 个线程:

In [8]: [t.start() for t in threads]
Out[8]: [None, None, None]

打印结果,如下,

当前线程t0,打印结束时间为:1582761727.4976637
当前线程t1,打印结束时间为:1582761727.4976637
当前线程t2,打印结束时间为:1582761727.498664
当前线程t0,打印结束时间为:1582761727.597949
当前线程t1,打印结束时间为:1582761727.597949
当前线程t2,打印结束时间为:1582761727.599801
当前线程t1,打印结束时间为:1582761727.6984522
当前线程t0,打印结束时间为:1582761727.6984522
当前线程t2,打印结束时间为:1582761727.7001588
当前线程t1,打印结束时间为:1582761727.7988598
当前线程t0,打印结束时间为:1582761727.7996202
当前线程t2,打印结束时间为:1582761727.8006535
当前线程t1,打印结束时间为:1582761727.8994005
当前线程t0,打印结束时间为:1582761727.900454
当前线程t2,打印结束时间为:1582761727.9024456

根据操作系统的调度算法,t0、t1、t2 三个线程,轮询获得 CPU 时间片。

抢夺全局变量

还有 69% 的精彩内容
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
支付 ¥2.99 继续阅读

推荐阅读更多精彩内容