线程是程序最小的执行单元;一个进程可以有多个线程,但是只有一个主线程。Python的标准库提供了两个模块:thread和threading,thread是低级模块,threading是高级模块,对thread进行了封装。绝大多数情况下,我们只需要使用threading这个高级模块。
import _thread # 多线程
import time
def go():
for i in range(5):
print(i,"-------")
time.sleep(1)
for i in range(5): # 同时执行5次
_thread.start_new_thread(go,()) # 前面是执行函数,后面是一个元组,可以不写前提是函数没有形参
for j in range(6): # 让主线程卡顿6秒
time.sleep(1)
print("over")
基于类实现多线程
import threading
class haha(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.num = 0
def run(self):
for _ in range(1000):
self.num += 1
print(self.num)
if __name__ =="__main__":
ts = []
for i in range(5):
t = haha()
t.start()
ts.append(t)
for i in ts:
t.join()
print('Over')
多个线程之间 内存是共享的,所以线程比进程轻量。多个线程是可以同时访问内存中的数据的,如果多个线程同时修改一个对象,这份数据可能会被破坏,Python的threading类中提供了Lock方法,它会返回一个锁对象,一般通过lock.acquire()来获取锁,通过lock.release()来释放锁,对于那种只允许一个线程操作 的数据,一般把对其的操作放在lock.acquire()和lock.release()中间。
import threading
num = 0
mutex = threading.Lock() # 创建一个锁,threading.Lock()是一个类
class Myhtread(threading.Thread):
def run(self):
global num
if mutex.acquire(1): # 如果锁成功,那么线程继续干活,如果锁失败,下面的线程一直等待锁成功,1,代表独占
for i in range(1000): # 数字小的时候还是不会产生线程冲突的
num += 1
mutex.release() # 释放锁,一定切记
print(num)
mythread = []
for i in range(5):
t = Myhtread()
t.start()
mythread.append(t)
for thread in mythread:
thread.join()
print("game over")
死锁:
import threading
import time
boymutex = threading.Lock() # 创建一个锁
girlmutex = threading.Lock() # 创建一个锁
class boy(threading.Thread):
def run(self):
if boymutex.acquire(1): # 锁定成功就继续执行,锁定不成功,就一直等待
print(self.name + "boy say i am sorry up")
# time.sleep(3) # 时间过短的话也可以并发执行,不会锁死
if girlmutex.acquire(1): # 锁定不成功,因为下面已经锁定
print(self.name + "boy say i am sorry down")
girlmutex.release()
boymutex.release()
class girl(threading.Thread):
def run(self):
if girlmutex.acquire(1): # 锁定成功就继续执行,锁定不成功,就一直等待
print(self.name + "girl say i am sorry up")
# time.sleep(3)
if boymutex.acquire(1): # 锁定不成功,同理上面已经锁定一直等待
print(self.name + "girl say i am sorry down")
boymutex.release()
girlmutex.release()
# 开启两个线程
# boy1 = boy() # Thread-1boy 第一个线程
# boy1.start()
# girl1 = girl()
# girl1.start()
'''
这种例子时间过短是无法很好的产生死锁
for i in range(10):
Mythread1().start()
Mythread2().start()
'''
for i in range(1000):
boy().start()
girl().start()
创建多线程
'''
第一种用函数创建多线程,但是需要处理让脚本主线程不死
import threading
import win32api
class Mythread(threading.Thread): # 继承threading.Thread类
def run(self): # 定义函数
win32api.MessageBox(0, "hello", 'joker', 0)
Mythd = []
for i in range(5):
t = Mythread() # 初始化
print(i)
t.start() # 开启
Mythd.append(t) # 将乱序线程(同时抢夺run这个函数)加入列表
for j in Mythd:
# 这里与顺序不同,上面显示所有的线程都加入Mthd列表(所以一次性跳出5个窗口,但是主线程还没死,因为有join卡住)。
# j是线程
j.join() # 这里主线程同时等待所有线程都执行完毕,才执行“game over”
print("game over")
'''
'''
第二种是基于类继承创建多线程
import threading
import win32api
class Mythread(threading.Thread): # 继承threading.Thread类
def run(self): # 重写threading.Thread类中的run函数
win32api.MessageBox(0,"hello",'joker',0)
for i in range(5): # 同时创建5个线程
t = Mythread() # 初始化
t.start() # 开启
while True:
pass
'''
'''
def show(i):
win32api.MessageBox(0,"这是一个测试","来自Joker",0)
threading.Thread(target=show,args=(i,)).start() # 切记这里的args是一个元组
threading.Thread(target=show,args=(i,)).start()
'''
# 基于函数构造实现多线程
import threading
import win32api
def show():
win32api.MessageBox(0, "这是一个测试", "来自Joker", 0)
# target=show是线程函数,args=()是参数
threading.Thread(target=show, args=()).start()
threading.Thread(target=show, args=()).start()
信号限制线程数量
import threading
import time
sem = threading.Semaphore(2) # 限制最大线程数为2个
def gothread():
with sem: # 锁定数量
for i in range(10):
print(threading.current_thread().name, i) # 打印线程名字
time.sleep(1)
for i in range(5):
threading.Thread(target=gothread).start() # 乱序执行多线程,就可以考虑为有些cpu牛逼些能够执行快一点
锁定匹配数量
import threading
# 为了合理利用资源
# 凑出线程数量,也就是说一定要至少凑成两个才能执行
# 换而言之,也就是说只有创建线程数是2,或者2的倍数才能全部执行
bar = threading.Barrier(2)
def sever():
print(threading.current_thread().name,"start")
bar.wait()
print(threading.current_thread().name,"end")
for i in range(3):
threading.Thread(target=sever).start()
'''
Thread-1 start
Thread-2 start
Thread-2 end
Thread-1 end
Thread-3 start
这里出现Thread-3 是因为锁定在"start"之后,所以最后面Thread-3 end 是无法出现的
'''
练习:
练习一:利用装饰器(睡眠五秒之后打印)
import threading
import time
def deco2(times):
def deco(func):
def warp(*args,**kwargs):
e = args[0]
time.sleep(times)
e.set()
return func(*args,**kwargs)
return warp
return deco
@deco2(5)
def A(e):
e.wait()
print('Hello World!')
if __name__=="__main__":
e = threading.Event()
t = threading.Thread(target=A,args=(e,))
t.start()
t.join()
练习二:猫眼电影top100
import requests
import threading
import re
class maoyan_top500(threading.Thread):
def __init__(self, start_, end_,lock):
threading.Thread.__init__(self)
self.headers = {
'User-Agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'
}
self.base_url = 'https://maoyan.com/board/4?offset=%d'
self.start_ = start_
self.end_ = end_
self.lock = lock
def run(self):
for offset in range(self.start_, self.end_, 10):
url = self.base_url % offset
response = requests.get(url, headers=self.headers)
html = response.text
info_list = self.get_Information(html)
with self.lock:
self.write(info_list)
print('offset {} OK !'.format(offset))
def get_Information(self, htm‘l):
information_list = []
for line in html.split('\n'):
if 'class="image-link"' in line:
movie_name = line.split('title="')[1].split('"')[0]
information_list.append(movie_name)
if 'class="integer"' in line:
res = re.search(
'<p class="score"><i class="integer">(\d\.)</i><i class="fraction">(\d)</i></p>',
line)
integer = res.group(1)
fraction = res.group(2)
score = integer + fraction
information_list.append(score)
return information_list
def write(self,info_list):
str_ = str(info_list) + '\n'
with open('res.txt',mode='a',encoding='utf8') as file:
file.write(str_)
if __name__ == "__main__":
threads = []
lock = threading.Lock()
for i in range(2):
t = maoyan_top500(start_=i * 50, end_=(i + 1) * 50,lock=lock)
t.start()
threads.append(t)
for t in threads:
t.join()
print('Over')
练习三:随机生成100个验证码放入本地
import threading
import random
class Myhtread(threading.Thread):
def __init__(self,lock):
threading.Thread.__init__(self)
self.lock = lock
self.list_ = []
def run(self):
for i in range(50):
res = random.randint(1000,10000)
self.list_.append(res)
with self.lock:
self.write(self.list_)
def write(self,num):
b = [str(x)+'\n' for x in num]
b = ''.join(b)
with open('res.txt',mode = 'a') as file:
file.write(b)
if __name__ =="__main__":
ts = []
lock = threading.Lock()
for i in range(2):
t = Myhtread(lock)
t.start()
ts.append(t)
for t in ts:
t.join()
print("Over")