并发与锁
多个线程共享数据的时候,如果数据不进行保护,那么可能出现数据不一致现象,使用锁,信号量、条件锁
互斥锁
1. 互斥锁,是使用一把锁把代码保护起来,以牺牲性能换取代码的安全性,那么Rlock后 必须要relase 解锁 不然将会失去多线程程序的优势
2. 互斥锁的基本使用规则:
信号量:
1. 调用relarse()信号量会+1 调用 acquire() 信号量会-1
可以理解为对于临界资源的使用,以及进入临界区的判断条件
2. semphore() :当调用relarse()函数的时候 单纯+1 不会检查信号量的上限情况。 初始参数为0
3. boudedsemphore():边界信号量 当调用relarse() 会+1 , 并且会检查信号量的上限情况。不允许超过上限
使用budedsemaphore时候不允许设置初始为0,将会抛出异常
至少设置为1 ,如consumer product 时候应该在外设置一个变量,启动时候对变量做判断,决定使不使用acquier
4. 信号量的基本使用代码:
全部的代码:
# -*- coding: utf-8 -*-"""Created on Mon Sep 9 21:49:30 2019@author: DGW-PC"""# 信号量解决生产者消费者问题import random;import threading;import time;# 声明信号量sema=threading.Semaphore(0);# 必须写参数 0 表示可以使用数sema2=threading.BoundedSemaphore(1);apple=1;def product():#生产者 global apple; apple=random.randint(1,100); time.sleep(3); print("生成苹果:",apple); #sema2.release(); # +1 if apple==1: pass else: sema2.release();#+ 1 def consumer(): print("等待"); sema2.acquire();# -1 if apple==1: pass else: print("消费:",apple);threads=[];for i in range(1,3): t1=threading.Thread(target=consumer); t2=threading.Thread(target=product); t1.start(); t2.start(); threads.append(t1); threads.append(t2);for x in threads: x.join();以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。