线程通信
cond只有一个,线程1线锁定cond,当线程1跑到i==5的时候,此时进入condition等待,将资源释放出来,这时候线程2进入,一口气全部跑完i,跑到最后以cond.notifly通知
将资源再放出来,此时线程1重新锁定
import threading
import time
def go1():
with cond:
for i in range(10):
time.sleep(1)
print(threading.current_thread().name, i)
if i == 5:
cond.wait() # 等待,只有在其他相同线程条件变量唤醒时才继续执行
print("hahahha")
def go2():
with cond: # 使用条件变量
for i in range(10):
time.sleep(1)
print(threading.current_thread().name, i)
cond.notify() # 通知唤醒其他线程
cond = threading.Condition() # 线程条件变量
threading.Thread(target=go1).start()
threading.Thread(target=go2).start()
线程调度
首先明确wait()调用后下面的程序是不会运行的,首先线程1线绑定cond,打印出0后,线程1进入等待(注意此时线程2并没有绑定),线程2绑定cond,打印出1后
notify给线程1唤醒wait(),(此时才打印出"haha"),同时线程2的wait激活进入等待,同时1打印出2,并唤醒线程2如此循环
import threading
import time
def go1():
with cond:
for i in range(0, 10, 2):
time.sleep(1)
print(threading.current_thread().name, i)
cond.wait()
# print("hahah")
cond.notify()
def go2():
with cond:
for i in range(1, 10, 2):
time.sleep(1)
print(threading.current_thread().name, i)
cond.notify()
cond.wait()
cond = threading.Condition() # 线程条件变量
threading.Thread(target=go1).start()
threading.Thread(target=go2).start()
wait后的代码不会运行,notify后的代码一定会运行
生产者与消费者模式
有多个生产者将商品放入队列,同时又多个消费者在队列的另一头获取商品
import threading
import time
import queue
q = queue.Queue(maxsize=10)
def producer(name): # 生产者
count = 1
while True:
q.put("骨头%s" % count)
print("生产了骨头", count)
count += 1
time.sleep(0.5)
def consumer(name): # 消费者
while True:
print("[%s]取到[%s]并且吃了它..." % (name, q.get()))
time.sleep(1)
p = threading.Thread(target=producer, args=("Tim",))
c1 = threading.Thread(target=consumer, args=("King",))
c2 = threading.Thread(target=consumer, args=("Wang2",))
c3 = threading.Thread(target=consumer, args=("Wang3",))
c4 = threading.Thread(target=consumer, args=("Wang4",))
c5 = threading.Thread(target=consumer, args=("Wang5",))
p.start()
c1.start()
c2.start()
c3.start()
c4.start()
c5.start()
定时通信
def show():
while True:
time.sleep(3)
print("say hello")
mythreading = threading.Timer(3, show).start() # 延时3秒启动show函数,只启动一次,不阻塞主线程
num = 0
while True:
print('第', num, "秒")
time.sleep(1)
num += 1
正则
常用正则匹配规则
\w-----匹配字母,数字以及下划线
\W----匹配非字母,数字,下划线的字符
\s-----匹配任意空白字符,等价于\t\n\r\f
\S-----匹配任意非空字符
\d-----匹配任意数字
\D----匹配任意非数字字符
\A----匹配字符串开头
\Z----匹配字符串结尾,存在换行时,只匹配到换行前的字符串
\z----匹配字符串结尾,存在换行时,会匹配换行符
\G—匹配最后匹配完成的位置
\n----匹配一个换行符
\t-----匹配一个制表符
^------匹配一行字符串的开头
$-----匹配一行字符串的结尾
.------匹配任意字符除了换行符
[…]—例:[acv]匹配a c v
[^…]–匹配不在[]中的字符
*------匹配0个或多个表达式
±----匹配1个或多个表达式
?-----匹配0个或1个前面的正则表达式定义的片段,非贪婪模式
{n}—精确匹配n个前面的表达式
a|b—匹配a或b
()-----匹配括号内的表达式
括号里的是目标函数
和正则相撞时用转译两个反斜杠
.*?没有问号表示贪婪模式
?表示非贪婪