锁的概念:
当多个线程同时进行任务时,为了保证不会有多个线程对同个数据进行操作造成不可预估的结果,所以有了锁的概念,我们通过锁来保证多个线程更加安全
lock=threading.Lock()#获得一个锁
cond1=threading.Condition(lock=lock)
condition的四个方法:
cond1.acquire()#上锁
cond1.wait() #等待
cond1.release() #解锁
cond1.notify() #唤醒
例如:
import threading import time lock=threading.Lock()#获得一个锁 cond=threading.Condition(lock=lock) class Thread1(threading.Thread): def run(self): for i in range(1,11): if i ==3: cond.acquire()#上锁 cond.wait()#等待 cond.release()#解锁 print(i) time.sleep(1) class Thread2(threading.Thread): def run(self): for i in range(30,19,-1): print(i) time.sleep(1) cond.acquire() cond.notify()#唤醒 cond.release() t1=Thread1() t2=Thread2() t1.start() t2.start()
生产者与消费者模式:
class HuoFu(threading.Thread): def run(self): #生产馒头 while True: condChiHuo.acquire() if len(guo)==0: for i in range(1,11): guo.append(i) print("伙夫生产第%d个馒头"%i) time.sleep(1) condChiHuo.notify_all() condChiHuo.release() class ChiHuo(threading.Thread): mantou=None def __init__(self,name): threading.Thread.__init__(self) self.name =name def run(self): #吃馒头 while True: condChiHuo.acquire() if len(guo)>0: mantou=guo.pop() time.sleep(1) else: #通知伙夫 condHuoFu.acquire() condHuoFu.notify() condHuoFu.release() condChiHuo.wait() condChiHuo.release() if mantou is not None: print("{0}在吃第{1}个馒头".format(self.name,mantou)) lock1=threading.Lock() condHuoFu=threading.Condition(lock1)#伙夫 lock2=threading.Lock() condChiHuo=threading.Condition(lock2)#吃货 huofu=HuoFu() huofu.start() handaohong=ChiHuo("小红") lingxiao=ChiHuo("小刚") laowang=ChiHuo("小王") handaohong.start() lingxiao.start() laowang.start()
正表达式:
re 模块使 Python 语言拥有全部的正则表达式功能。
re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。
import re
print(re.match('www', 'www.runoob.com').span()) # 在起始位置匹配 加.span()输出的是下标
print(re.match('com', 'www.runoob.com')) # 不在起始位置匹配
import re
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)# .*贪婪模式 .*?懒惰模式
if matchObj:
print ("matchObj.group() : ", matchObj.group())
print ("matchObj.group(1) : ", matchObj.group(1))
print ("matchObj.group(2) : ", matchObj.group(2))
else:
print ("No match!!")