Python解决GIL锁的办法

GIL (Global Intercepto Lock)全局解释器锁

当机器无论是有几个核心,Python多线程都只会用到其中一个核心。利用htop命令可以测试出来。

这个并没有解决数据共享出现不同步的问题

#-*- coding:utf-8 -*-
import threading

#子线程死循环
def test():
    while True:
        pass

t1 = threading.Thread(target=test)
t1.start()

#主线程死循环
while True:
    pass

代码测试无论开几个,都只是跑满cpu100%,相当于一核心。

解决方法:
1. 使用多进程执行,此将要面临解决共享数据的问题,多用queue或pipe解决;
2. 使用Python多线程load C的module执行。

from ctypes import *
form threading import Thread

#加载动态库
lib = cdll.LoadLibrary("./libdeadloop.so")

#创建一个子线程,让其执行c语言编写的函数,此函数是一个死循环
t = Thread(target=lib.DeadLoop)
t.start()

while True:
    pass

猜你喜欢

转载自blog.csdn.net/budong282712018/article/details/79968320
今日推荐