线程:
1.创建线程:
创建一个新的Thread对象的实例。Thread的构造函数接受一个参数:
Thread DummyThread = new Thread( new ThreadStart(dummyFunction) );
2.执行线程:
使用Threading命名空间里的start方法来运行线程:
DummyThread.Start ();
3.暂停线程:
使得线程暂停给定的秒
DummyPriorityThread.Sleep(
多线程速度:
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
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
类线程顺序风格
import threading
import win32api
class Mythread(threading.Thread): # 继承threading.Thread类
def run(self): # 定义函数
win32api.MessageBox(0,"hello",'joker',0)
for i in range(5):
t = Mythread() # 初始化
t.start() # 开启 [等待一个线程执行完毕,再执行下一个线程,可以阻止脚本主线程死掉,也可以防止线程冲突]
t.join()
print("game over")
t.join() 如果将其放在外部的不确定因素是,系统给for 循环和下面的代码锁定了一片内存,当循环执行完成之后,内存就开锁了,但是里面的东西还依然存在,所以才结束一个窗体,game over就出来了,,就和删除文件后,内存中可能还有文件一样的道理
类线程乱序风格
import threading
import win32api
class Mythread(threading.Thread): # 继承threading.Thread类
def __init__(self, num):
threading.Thread.__init__(self) # 父类初始化
self.num = num
def run(self): # 定义函数
win32api.MessageBox(0, "hello" + str(self.num), 'joker', 0)
print(self.getName()) # 获取线程名
Mythd = []
for i in range(5):
t = Mythread(i) # 初始化
print(i)
t.start() # 开启
Mythd.append(t) # 将乱序线程(同时抢夺run这个函数)加入列表
for j in Mythd: #j是线程
j.join() # 这里主线程同时等待所有线程都执行完毕,才执行“game over”
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()
for i in range(1000):
boy().start()
girl().start()
Rlock
import threading
num = 0
mutext = threading.RLock() # PLOCK避免单线程死锁
class Mythreading(threading.Thread):
def run(self):
global num
if mutext.acquire(1): #加锁
num += 1
print(self.name, num)
if mutext.acquire(1):
num += 1000
mutext.release() #解锁
mutext.release()
for i in range(5): # 开启5个进程
t = Mythreading()
t.start()
创建多线程
第一种用函数创建多线程
threading.Thread() 一般接收两个参数:
线程函数名:要放置线程让其后台执行的函数,由我们自已定义,注意不要加();
线程函数的参数:线程函数名所需的参数,以元组的形式传入。若不需要参数,可以不指定。
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)
for j in Mythd:
j.join() # 这里主线程同时等待所有线程都执行完毕,才执行“game over”
print("game over")
第二种是基于类继承创建多线程
自定义一个类,对于这个类有两点要求,
必须继承 threading.Thread 这个父类;
必须覆写 run 方法。
import time
from threading import Thread
class MyThread(Thread):
def __init__(self, name="Python"):
super().__init__()
self.name=name
def run(self):
for i in range(2):
print("hello", self.name)
time.sleep(1)
if __name__ == '__main__':
# 创建线程01,不指定参数
thread_01 = MyThread()
# 创建线程02,指定参数
thread_02 = MyThread("MING")
thread_01.start()
thread_02.start()
线程通信
import threading
import time
def goevent():
e = threading.Event() # 事件
def go():
e.wait() # 等待事件,线程卡顿,等待set消息
print("go")
threading.Thread(target=go).start() # 需要创建一个线程
return e
t = goevent()
time.sleep(3)
t.set() # 激发事件
import threading
NUM=0
class Jack(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global NUM
for _ in range(1000):
NUM+=1
print(NUM)
if __name__=="__main__":
for i in range(5):
t=Jack()
t.start()
while 1:
pass
import threading
import random
class Jack(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.randrange(1000,9999)
print(res)
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=Jack(lock)
t.start()
ts.append(t)
for t in ts:
t.join()
print('Over')
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,arg=(e,))
t.start()
t.join()
爬取电影
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, 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
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')