11-2 Python多线程threading
2018-08-26 本文已影响0人
正在努力ing
分进程设置
工具: threading包
1 先写需要分进程运行的函数或者类
def maigic():
pass
2 实例化threading,得到新的进程
threadone = threading.Thread(target=maigic)
此时还可以接受arg参数
import threading
import time
def get_html():
print("get_html is start ")
time.sleep(3)
print("get_html is end")
def get_url():
print("get_url is start")
time.sleep(2)
print("get_url is end")
thread1 = threading.Thread(target=get_html)
thread2 = threading.Thread(target=get_url)
start_time = time.time()
print("start time is {}".format(start_time))
thread1.start()
thread2.start()
end_time = time.time()
print("end time is {}".format(end_time-start_time))
>>>
start time is 1532486991.7209127
get_html is start
get_url is start
end time is 0.0004737377166748047
get_url is end
get_html is end
此时整个程序存在三个进程,
1 主进程:程序运行
2 进程1 : thread1
3 进程2 : thread2
三个进程属于并发的,主程序会等到其余两个进程结束后,主程序才会结束
但是主程序是执行完所有语句然后等待其余进程的结束,而不是停在进程语句哪里等待
此时可以设置守护进程--优先级在主进程之下,主进程可以kill掉守护进程
thread1.setDaemon(True) #将thread2设为守护进程
thread1.join() # 等待进程结束
import threading
import time
def get_html():
print("get_html is start ")
time.sleep(3)
print("get_html is end")
def get_url():
print("get_url is start")
time.sleep(2)
print("get_url is end")
thread1 = threading.Thread(target=get_html)
thread2 = threading.Thread(target=get_url)
thread1.setDaemon(True)
thread2.setDaemon(True) # 将thread2设为守护进程--优先级在主进程之下,主进程可以kill掉守护进程
start_time = time.time()
print("start time is {}".format(start_time))
thread1.start()
thread2.start()
thread1.join() # 等待进程结束
thread2.join()
end_time = time.time()
print("end time is {}".format(end_time-start_time))
>>>
start time is 1532486991.7209127
get_html is start
get_url is start
get_url is end
get_html is end
end time is 0.0004737377166748047
有了守护进程之后,主程序就会在自身结束后,(不管守护进程还是不是在运行)kill守护进程
但是有了 :
thread1.join() # 等待进程结束
thread2.join()
主程序就会停在join哪里,等待结束后,再继续执行
改进把变成类,自定义类继承threading.Thread 类
此时需要重载run方法 , run方法就是运行逻辑
import threading
import time
class Thread_case(threading.Thread):
def __init__(self,name,time):
self.mytime = time
self.myname = name
super().__init__(name=name)
def run(self):
print("{name} is start ".format(name=self.myname))
time.sleep(self.mytime)
print("{name} is end".format(name=self.myname))
thread1 = Thread_case("get_url",3)
thread2 = Thread_case("get_html",2)
thread1.setDaemon(True)
start_time = time.time()
print("start time is {}".format(start_time))
thread1.start()
thread2.start()
# thread1.join() # 等待进程结束
# thread2.join()
end_time = time.time()
print("end time is {}".format(end_time-start_time))
>>>
start time is 1532496367.0786047
get_url is start
get_html is start
end time is 0.0009756088256835938
get_html is end