import threading
import win32api
classMythread(threading.Thread):# 继承threading.Thread类defrun(self):# 重写threading.Thread类中的run函数
win32api.MessageBox(0,"hello",'joker',0)for i inrange(5):# 同时创建5个线程
t = Mythread()# 初始化
t.start()# 开启whileTrue:pass
线程冲突
import _thread
num =0defadd():for _ inrange(1000000):global num
num +=1print(num)'''
for j in range(5):
add()
'''for i inrange(5):
_thread.start_new_thread(add,())# 这里就是线程冲突,5个线程同时抢夺num的资源,导致最后结果错误'''
1144840
1488805
1671079
1700819
1920182
'''whileTrue:# 防止主线程不死pass
import threading
import time
boymutex = threading.Lock()# 创建一个锁
girlmutex = threading.Lock()# 创建一个锁classboy(threading.Thread):defrun(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()classgirl(threading.Thread):defrun(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 inrange(1000):
boy().start()
girl().start()
爬猫眼电影
import requests
import threading
import re
classmaoyan_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
defrun(self):for offset inrange(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))defget_Information(self, html):
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
defwrite(self,info_list):
str_ =str(info_list)+'\n'withopen('res.txt',mode='a',encoding='utf8')asfile:file.write(str_)if __name__ =="__main__":
threads =[]
lock = threading.Lock()for i inrange(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')