from multiprocessing import Process
import os# 子進程要執行的代碼
def run_proc(name):print('Run child process %s (%s)...' % (name, os.getpid()))if __name__=='__main__':print('Parent process %s.' % os.getpid())p = Process(target=run_proc, args=('test',))print('Child process will start.')p.start()p.join()print('Child process end.')
Pool
p=Pool(5)
p.apply_async(func,**args)
p.close()
p.join()
from multiprocessing import Pool
import os, time, randomdef long_time_task(name):print('Run task %s (%s)...' % (name, os.getpid()))start = time.time()time.sleep(random.random() * 3)end = time.time()print('Task %s runs %0.2f seconds.' % (name, (end - start)))if __name__=='__main__':print('Parent process %s.' % os.getpid())p = Pool(4)for i in range(5):p.apply_async(long_time_task, args=(i,))print('Waiting for all subprocesses done...')p.close()p.join()print('All subprocesses done.')
Thread 涉及模塊:threading
Thread
t = threading.Thread(target=xxx,name=xxx,args=(xxx,xxx))
t.start()
t.join()
threading.curent_thread().name
l = threading.Lock()
l.acquire()
l.release()
import time, threading# 新線程執行的代碼:
def loop(s):print(s)print('thread %s is running...' % threading.current_thread().name)n = 0while n < 5:n = n + 1print('thread %s >>> %s' % (threading.current_thread().name, n))time.sleep(1)print('thread %s ended.' % threading.current_thread().name)print('thread %s is running...' % threading.current_thread().name)
t = threading.Thread(target=loop, name='LoopThread', args=('a',))
t.start()
t.join()
print('thread %s ended.' % threading.current_thread().name)
def sim_add(a):return a[0]+a[1]from concurrent.futures import ThreadPoolExecutor
import concurrent.futureswith ThreadPoolExecutor(max_workers=1) as t1:future1 = t1.submit(sim_add,(1,2))print(future1.result())print()
var = [(1,2),(10,20),(100,200)]
with ThreadPoolExecutor(max_workers=2) as t:future = {t.submit(sim_add,tem): tem for tem in var}for parameter,res in zip(var,concurrent.futures.as_completed(future)):print("sim_add %s,return %s" % (parameter,res))# 多次submit,不接收結果但是又想全部執行完# concurrent.futures.wait()
print()
with ThreadPoolExecutor(max_workers=2) as t:for f in t.map(sim_add,[(1,2),(2,3)]):print(f)