并发与锁

  • a. 多个线程共享数据的时候,如果数据不进行保护,那么可能出现数据不一致现象,使用锁,信号量、条件锁
  • b.
  • c.互斥锁
    1. 互斥锁,是使用一把锁把代码保护起来,以牺牲性能换取代码的安全性,那么Rlock后 必须要
    relase 解锁 不然将会失去多线程程序的优势
    2. 互斥锁的基本使用规则:
1 import threading
2 # 声明互斥锁
3 lock=threading.Rlock();
4 def handle(sid):# 功能实现代码
5 lock.acquire() #加锁
6 # writer codeing
7 lock.relase() #释放锁
  • 8
    信号量:
    1. 调用relarse()信号量会+1 调用 acquire() 信号量会-1
    a. 可以理解为对于临界资源的使用,以及进入临界区的判断条件
    2. semphore() :当调用relarse()函数的时候 单纯+1 不会检查信号量的上限情况。 初
    始参数为0
    3. boudedsemphore():边界信号量 当调用relarse() 会+1 , 并且会检查信号量的上
    限情况。不允许超过上限
    a. 使用budedsemaphore时候不允许设置初始为0,将会抛出异常
    b. 至少设置为1 ,如consumer product 时候应该在外设置一个变
    量,启动时候对变量做判断,决定使不使用acquier
    4. 信号量的基本使用代码:
1 # 声明信号量:
2 sema=threading.Semaphore(0); #无上限检查
3 sema=threading.BuderedSeamphore(1) #有上限检查设置
4 5
apple=1
6 def consumner():
7 seam.acquire(); # ‐1
8 9
if apple==1:
10 pass
11 else: sema2.release();#+ 1
12 def product():
13 seam.relarse(); # +1
14 if apple==1:
15 pass
16 else:
17 print("消费:",apple);
18

  • 全部的代码:
# -*- 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();