多线程 lock
"""
__time__ = '2021/6/21 23:09'
__author__ = 'Liang'
Lock 锁
使用 包裹代码 with lock:
"""
import threading
import time
lock = threading.Lock()
class Account:
def __init__(self, blance):
self.blance = blance
def draw(account:Account, amount):
with lock:
if account.blance >= amount:
time.sleep(0.1)
print(threading.current_thread().name,"取钱成功")
account.blance -= amount
print(threading.current_thread().name,
"余额", account.blance)
else:
print(threading.current_thread().name, "取钱失败")
if __name__ == '__main__':
account = Account(1000)
ta = threading.Thread(target=draw, args=(account, 800))
tb = threading.Thread(target=draw, args=(account, 800))
ta.start()
tb.start()
线程池 ThreadPoolExecutor
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210622111128484.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTQwMDU5Mg==,size_16,color_FFFFFF,t_70)
"""
__time__ = '2021/6/21 23:37'
__author__ = 'Liang'
线程池的使用
concurrent.futures.ThreadPoolExecutor()
map 的使用
submit 的使用
"""
import concurrent.futures
import blog_spider
with concurrent.futures.ThreadPoolExecutor() as pool:
htmls = pool.map(blog_spider.crawl, blog_spider.urls)
htmls = list(zip(blog_spider.urls, htmls))
for url, html in htmls:
print(url, len(html))
print("craw over")
with concurrent.futures.ThreadPoolExecutor() as pool:
futures = {}
for url, html in htmls:
future = pool.submit(blog_spider.parse, html)
futures[future] = url
for future in concurrent.futures.as_completed(futures):
url = futures[future]
print(url, future.result())