GIL全局解释器锁

2019-05-30  本文已影响0人  ___大鱼___

python中一个线程对应C语言的一个线程 CPython实现的多线程

GIL使得同一个时刻只有一个线程在一个CPU上执行字节码 无法将多个线程映射到多个cpu上 这就体现不了我们多核的优势 效率变慢

GIL会根据执行的字节码以及时间片释放GIL,GIL会在遇到io操作时主动释放

setDaemon(True)守护线程

p = threading.Thread(target=test,)
    p.setDaemon(True)   # 守护线程  主线程结束后义无反顾的关闭子线程无论子线程执行完没有
p.join()   # 阻塞线程 等线程运行结束才会执行后面代码
# coding: utf-8


# 对于io操作来说,多线程和多进程差别不大
# 1.通过thread类实例化
# 2.通过继承Thread来实现多线程

import threading

def test():
    pass


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

    # 重写run方法
    def run(self):
        print 'thread1执行了。。'


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

    # 重写run方法
    def run(self):
        print 'thread2执行了。。'


if __name__ == '__main__':
    thread1 = GetDetailHtml('中国')
    thread2 = GetDetailUrl('地球')

    thread1.start()
    thread2.start()
上一篇 下一篇

猜你喜欢

热点阅读