多线程,多进程,线程池编程
一,GIL
CPython 解释器本身就不是线程安全的,因此有全局解释器锁(GIL),一次只允许使用一个线程执行 Python 字节码。因此,一个 Python 进程通常不能同时使用多个 CPU 核心。
这是 CPython 解释器的局限,与 Python 语言本身无关。Jython 和 IronPython 没有这种限制。
不过,目前最快的 Python 解释器 PyPy 也有 GIL
然而,标准库中所有执行阻塞型 I/O 操作的函数,在等待操作系统返回结果时都会释放 GIL。这意味着在 Python 语言这个层次上可以使用多线程,而 I/O 密集型 Python 程序能从中受益:一个 Python 线程等待网络响应时,阻塞型 I/O 函数会释放 GIL,再运行一个线程。
Python 标准库中的所有阻塞型 I/O 函数都会释放 GIL,允许其他线程运行。time.sleep() 函数也会释放 GIL。因此,尽管有GIL,Python 线程还是能在 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()
三,线程间的通信
…看我的网络编程的博客