谈谈python多线程编程

谈谈python多线程编程

Python中GIL概念

Python(CPython)不是线程安全的,所以我们需要一个GIL(Global interpreter Lock),来保证数据完性和安全性。也就是同一时间内同一核CPU中只能有一个GIL。

Threading的GIL机制分析

1、当一个线程A达到GIL的阀值时间就会释放GIL,这个时间其他等待的线程就会被唤醒来争抢这个GIL的使用权。如查在争抢的过程中还是线程A抢到了个GIL,那个释放和争抢的时间也就白白的浪费了,而且GIL切换的成本很高。
2、因为GIL的原因无论你机器是多少核的CPU一个任务只能运行在一个CUP上。

multiprocessing运行分析

进程中就不会有GIL的问题,因为第个进程都有自己独立的GIL,所以不会争抢。

实例分析

例1


import threading
import multiprocessing
import os

def test_funt():
    count = 0
    while True:
       count += 1


def multithread():
    for _ in range(os.cpu_count()):
        t1 = threading.Thread(target=test_funt)
        t1.start()

if __name__ == '__main__':
    multithread()

运行 例1代码,按照我们理想的状态cpu应该占用达到100% 但是并没有,如下图:
在这里插入图片描述

例2 (运行时要小心,容易死机)


import threading
import multiprocessing
import os

def test_funt():
    count = 0
    while True:
       count += 1

def multiproc():
    for _ in range(os.cpu_count()):
        t = multiprocessing.Process(target=test_funt)
        t.start()

if __name__ == '__main__':
    multiproc()

运行 例2代码,CPU占用达到100% ,充分得用多核CPU的优势,如下图:
在这里插入图片描述

Threading和multiprocessing在实际开发过程中应用场景:

Threading:如果大量的I/O工作时用 例如爬虫
multiprocessing:如果有很高的CPU运算时用。

猜你喜欢

转载自blog.csdn.net/weixin_39956308/article/details/85001278