multi_threading [多线程] 单独一个教程 join 的作用是主线程等待子线程的结束
import threading import time from queue import Queue def thread_job(): print( This is an added Thread number is %s %threading.current_thread()) print( T1 start ) for i in range(10): time.sleep(0.1) print( T1 finish ) # 多线程 def T2_job(): print( T2 startn ) print( T2 finishn ) def main(): add_thread threading.Thread(target thread_job) thread2 threading.Thread(target T2_job) add_thread.start() thread2.start() # join的作用是等待运行完执行后续代码 # add_thread.join() thread2.join()#主函数是否会等待线程结束 print( all done ) # print(threading.active_count()) # print(threading.enumerate()) # print(threading.current_thread()) if __name__ __main__ : main()
同类拆分任务效率提升
multi_process [多核] 多进程的使用
注意其中的队列的put()
import multiprocessing as mp q mp.Queue() def job(q): res 0 for i in range(1000): res i i**2 i**3 q.put(res) if __name__ __main__ : p1 mp.Process(target job,args (q,)) p2 mp.Process(target job, args (q,)) p1.start() p2.start() p1.join() p1.join() res1 q.get() res2 q.get() print(res1 res2)
多进程测试时间
import multiprocessing as mp import threading as td import time def job(q): res 0 for i in range(10000000): res i i**2 i**3 q.put(res) def multcore(): q mp.Queue() p1 mp.Process(target job,args (q,)) p2 mp.Process(target job, args (q,)) p1.start() p2.start() p1.join() p2.join() res1 q.get() res2 q.get() print(res1 res2) def normal(): res 0 for _ in range(2): for i in range(10000000): res i i ** 2 i ** 3 print( normal ,res) def multithread(): q mp.Queue() t1 td.Thread(target job,args (q,)) t2 td.Thread(target job, args (q,)) t1.start() t2.start() t1.join() t2.join() res1 q.get() res2 q.get() print( multithread ,res1 res2) if __name__ __main__ : t1 time.perf_counter() multcore() t2 time.perf_counter() print( multicore ,t2-t1)



