python高级编程(9) - 迭代器和生成器

多线程,多进程,线程池编程

一,GIL

CPython 解释器本身就不是线程安全的,因此有全局解释器锁(GIL),一次只允许使用一个线程执行 Python 字节码。因此,一个 Python 进程通常不能同时使用多个 CPU 核心。

这是 CPython 解释器的局限,与 Python 语言本身无关。JythonIronPython 没有这种限制。
不过,目前最快的 Python 解释器 PyPy 也有 GIL

然而,标准库中所有执行阻塞型 I/O 操作的函数,在等待操作系统返回结果时都会释放 GIL。这意味着在 Python 语言这个层次上可以使用多线程,而 I/O 密集型 Python 程序能从中受益:一个 Python 线程等待网络响应时,阻塞型 I/O 函数会释放 GIL,再运行一个线程。

Python 标准库中的所有阻塞型 I/O 函数都会释放 GIL,允许其他线程运行。time.sleep() 函数也会释放 GIL。因此,尽管有GILPython 线程还是能在 I/O 密集型应用中发挥作用。

二,多线程实现方法

Threading 实现多线程

import threading
import time

def get_detail_html(url):
    print('get detail html started')
    time.sleep(2)
    print('get detail url end')

def get_detail_url(url):
    print('get detail url started')
    time.sleep(2)
    print('get detail url end')


if __name__ == '__main__':
    thread1 = threading.Thread(target=get_detail_html, args=(None, ))
    thread2 = threading.Thread(target=get_detail_url, args=(None, ))
    thread1.start()
    thread2.start()
class GetDetailHtml(threading.Thread):
    def __init__(self, name):
        super().__init__(name=name)

    def run(self):
        print('get detail html started')
        time.sleep(2)
        print('get detail url end')

class GetDetailUrl(threading.Thread):
    def __init__(self, name):
        super().__init__(name=name)

    def run(self):
        print('get detail url started')
        time.sleep(2)
        print('get detail url end')

if __name__ == '__main__':
    thread1 = GetDetailHtml('threading1')
    thread2 = GetDetailUrl('threading2')
    thread1.start()
    thread2.start()

三,线程间的通信

…看我的网络编程的博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值