import threading import time def fun(n): print("task",n) time.sleep(2) print("task done",n) start_time = time.time() t_objs = [] for i in range(50): t = threading.Thread(target=fun,args=("task_%s"%i,)) t.start() t_objs.append(t) for t in t_objs: t.join() print("all task has done") print("cost",time.time() - start_time)
1,实现了多线程的并发,主进程在等待各个线程执行结束之后才继续往下执行
2 ,t.join()让进程等待当前线程结束。
3 ,线程的实例
》》》》》》》》》》》》》线程2
import threading import time class MyThread(threading.Thread): def __init__(self,n,sleep_time): super (MyThread,self).__init__() self.n = n self.sleep_time = sleep_time def run(self): print("run task",self.n) time.sleep(self.sleep_time) print("task has done",self.n) t1 = MyThread("t1",2) t2 = MyThread("t2",4) t1.start() t2.start() t1.join() print("main process")
1,类的方式定义多线程并发
》》》》》》》》线程3
import threading,time def run(n): print("task ",n) time.sleep(2) print("task has done",n,threading.current_thread())#打印当前进程 start_time = time.time()#主进程开始时间 t_objs = []#存线程实例 for i in range(50): t = threading.Thread(target=run,args=("task %s"%i,)) t.setDaemon(True)#把当前线程设置为守护线程 t.start() t_objs.append(t) for t in t_objs: t.join() print("all threads has done",threading.active_count(),threading.current_thread()) print("cost",time.time()-start_time)
1,t.setDaemon(True)#把当前线程设置为守护线程
2,threading.active_count() 活跃的线程
threading.current_thread() 当前执行的线程
三》》》多进程
import multiprocessing,time,threading def fun(): print("线程开始") print(threading.get_ident()) print("线程结束") def run(name): time.sleep(2) print("hellow world",name) t = threading.Thread(target=fun,) t.start() if __name__ == '__main__': for i in range(5): p = multiprocessing.Process(target=run, args=("bob%s"%i,)) p.start() # p = multiprocessing.Process(target = run,args=("bob",)) # p.start() # p.join()
1.启动5个进程,每个进程中启动一个线程
》》》》GET 进程id
from multiprocessing import Process import os def info(title): print(title) print("moudle name",__name__) print("parent process",os.getppid()) print("process id",os.getpid()) print(" ") def f(name): info("called from child process function") print("hellow ",name) if __name__=='__main__': info("main process line") p = Process(target=f,args=("cero",)) p.start() p.join()
》》》》