基于Cpython的全局解释器锁(GIL),死锁和递归锁,信号量, event事件,队列queue几种进出模式

博客介绍了Python并发编程中的相关知识,包括GIL(全局解释器锁),对比了Gil与普通锁,还涉及死锁与递归锁、event事件、信号量以及几种不同的queue,这些内容对理解Python并发机制有重要意义。

GIL(全局解释器锁)

"""
In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple
native threads from executing Python bytecodes at once. This lock is necessary mainly
because CPython’s memory management is not thread-safe. (However, since the GIL
exists, other features have grown to depend on the guarantees that it enforces.)
"""
"""
GIL是一个互斥锁:保证数据的安全(牺牲效率来换取数据的安全)
阻止同一个进程内,多个线程同时执行(不能并行但能够实现并发)
并发:看起来像同时进行(其实是快速切换并保存当前状态)
GIL全局解释器存在的原因因为Cpython解释器的内存管理不是线程安全的

垃圾回收机制:
    1.引用计数
    2.标记清除
    3.分代回收
同一个进程下的多个线程不能实现并行,但能实现并发,多个线程下的线程能够实现并行。

python多线程是不是没用了?
四个任务:计算密集型任务,每任务个耗时10s。
单核情况:
    多线程好一点,消耗的资源少
多核情况:
    多线程好一点
多线程和多进程都有自己的优点,根据项目需求合理选择。

"""
# 计算密集型
# from multiprocessing import Process
# from threading import Thread
# import os,time
#
#
# def work():
#     res = 0
#     for i in range(100):
#         res *= i
#
# if __name__ == '__main__':
#     l = []
#     print(os.cpu_count())
#     start = time.time()
#     for i in range(4):
#         # p = Process(target=work)
#         p = Thread(target=work)
#         l.append(p)
#         p.start()
#     for p in l:
#         p.join()
#     stop = time.time()
#     print('run time is %s'%(stop-start))

# 执行结果:
# 进程:
# 4
# run time is 6.02131462097168
# 线程:
# 4
# run time is 0.21412372589111328

# IO密集型
# from  multiprocessing import Process
# from  threading import Thread
# import os,time
#
#
# def work():
#     time.sleep(2)
#
# if __name__ == '__main__':
#     l = []
#     print(os.cpu_count())
#     start = time.time()
#     for i in range(100):
#         p = Process(target=work) #104.06727409362793
#         # p = Thread(target=work) # 2.0227677822113037
#         l.append(p)
#         p.start()
#     for p in l:
#         p.join()
#     stop = time.time()
#     print('run time is %s' %(stop - start))

Gil与普通锁

from threading import Thread,Lock
import time


mutex = Lock()
n = 100
def task():
    global n
    mutex.acquire()
    tmp = n
    time.sleep(0.1)
    n = tmp - 1
    mutex.release()

t_list = []
for i in range(100):
    t = Thread(target=task)
    t.start()
    t_list.append(t)
for t in t_list:
    t.join()

print(n)

"""
对于不同的数据,想要保证安全,需要加不同的锁处理
GIL并不能保证数据的安全,他是对Cpython解释器加锁,针对的是线程
保证同一进程下多个线程之间的安全
"""

死锁与递归锁

from threading import Thread,Lock,RLock
import time

"""
自定义锁一次acquire必须对应一次relaese,不能连续acquire
递归锁可以连续的acquire,每acquire一次计数加一:针对第一个抢到我的人

"""
import random

# mutexA = Lock()
# mutexB = Lock()

mutexA = mutexB = RLock() # 抢锁之后会有一个计数,抢一次,计数加一,针对一个抢到我的人

class MyThread(Thread):
    def run(self):
        self.func1()
        self.func2()

    def func1(self):
        mutexA.acquire()
        print('%s 抢到A锁了' % self.name)
        mutexB.acquire()
        print('%s 抢到B锁了' % self.name)
        mutexA.release()
        print('%s 释放A锁了' % self.name)
        mutexB.release()
        print('%s 释放B锁了' % self.name)

    def func2(self):
        mutexB.acquire()
        time.sleep(1)
        print('%s 抢到B锁了' % self.name)
        mutexA.acquire()
        print('%s 抢到A锁了' % self.name)
        mutexA.release()
        print('%s 释放A锁了' % self.name)
        mutexB.release()
        print('%s 释放B锁了' % self.name)
for i in range(100):
    t = MyThread()
    t.start()

event事件

import random
from threading import Event, Thread
import time


event = Event()

def light():
    print('红灯亮着!')
    time.sleep(3)
    event.set() # 解除阻塞,给我的event发了一个信号
    print('绿灯亮了!')

def car(i):
    print('%s s2q正在等待红灯' % i)
    event.wait() # 阻塞
    print('%s s2q开始飙车了!'% i)

t1 = Thread(target=light)
t1.start()

for i in range(10):
    t = Thread(target=car, args=(i,))
    t.start()

信号量

from threading import Thread,Semaphore
import time
import random


sm = Semaphore(5) # 五个厕所五把锁
# 跟普通的互斥锁的区别:
# 普通的互斥锁是独立卫生间,所有人抢一把锁
# 信号量 公共卫生间 有多个坑,所有人抢多把锁

def task(name):
    sm.acquire()
    print('%s正在上厕所!'% name)
    # 模拟上厕所耗时
    time.sleep(random.randint(1,5))
    sm.release()

if __name__ == '__main__':
    for i in range(20):
        t= Thread(target=task, args=('sg %s号'% i,))
        t.start()

几种不同的queue

import queue

# 1.普通q
# 2.先进后出q
# 3.优先级q

# 先进先出
# q = queue.Queue(3)
# q.put(1)
# q.put(2)
# q.put(3)
# print(q.get())
# print(q.get())
# print(q.get())

# 先进后出
# q = queue.LifoQueue(5)
# q.put(1)
# q.put(2)
# q.put(3)
# q.put(4)
# q.put(5)
# print(q.get())

# 优先级q
q = queue.PriorityQueue()
q.put((10, 'a'))
q.put((-1, 'b'))
q.put((-6, 's2g'))
print(q.get())
print(q.get())
print(q.get())

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值