线程同步
同时对数据进行修改防止并发
锁使多线程任务更加安全
Condition:上锁(acquire())等待(wait())解锁(release())唤醒(notify(),notify_all())
创键锁:lock=threading.Lock()
threading.Condition(lock=Lock)
- 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()
生产者和消费者模式
吃货与伙夫
- import threading
- import time
- list=[]
-
- lock=threading.Lock()
- huofuCon=threading.Condition(lock=lock)
- lock2=threading.Lock()
- chihuoCon=threading.Condition(lock=lock2)
- class Huofu(threading.Thread):
- def run(self):
-
- while True:
- chihuoCon.acquire()
- for i in range(1,11):
- list.append(i)
- print("伙夫生产第{0}个馒头".format(i))
- time.sleep(1)
-
- huofuCon.acquire()
- chihuoCon.notify_all()
- chihuoCon.release()
- huofuCon.wait()
- huofuCon.release()
- mantou=None
- class Chihuo(threading.Thread):
- def __init__(self,name):
- threading.Thread.__init__(self)
- self.name=name
- def run(self):
-
- while True:
- chihuoCon.acquire()
- if len(list)==0:
- huofuCon.acquire()
- huofuCon.notify()
- huofuCon.release()
- chihuoCon.wait()
- chihuoCon.release()
- chihuoCon.acquire()
- if len(list)>0:
- mantou=list.pop()
- print("{0}在吃第{1}个馒头".format(threading.current_thread().name,mantou))
- time.sleep(1)
- chihuoCon.release()
- huofu=Huofu()
- chihuo1=Chihuo('吃货1')
- chihuo2=Chihuo('吃货2')
- chihuo3=Chihuo('吃货3')
- huofu.start()
- chihuo1.start()
- chihuo2.start()
- chihuo3.start()
正则表达式
re.M 多行匹配,影响 ^ 和 $
re.I 使匹配对大小写不敏感
-
- import re
- print(re.match('www', 'www.runoob.com').span())
- print(re.match('com', 'www.runoob.com'))
-
-
- 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!!")
-
- import re
- print(re.search('www', 'www.runoob.com').span())
- print(re.search('com', 'www.runoob.com').span())
-
- import re
- line = "Cats are smarter than dogs";
-
- searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
-
- if searchObj:
- print ("searchObj.group() : ", searchObj.group())
- print ("searchObj.group(1) : ", searchObj.group(1))
- print ("searchObj.group(2) : ", searchObj.group(2))
- else:
- print ("Nothing found!!")