multiprocessing
from multiprocessing import Pool import os,time,random def 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('waitng for all subprocesses done...') p.close() p.join() print('all subprocesses done')
threading
import time,threading def loop(): print('thread %s is running...'% threading.current_thread().name) n = 0 while n<5: n += 1 print('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') t.start() t.join() print('thread %s ended'% threading.current_thread().name)
lock
import time,threading #假定这是银行存款 balance = 0 def change_it(n): #先存后取,结果应是0 global balance balance += n balance -= n # def run_thread(n): # for i in range(100000): # change_it(n) # lock = threading.Lock() def run_thread(n): for i in range(100000): #先要获取锁 lock.acquire() try: #可以放心改 change_it(n) finally: #改完了一定要释放锁 lock.release() # t1 = threading.Thread(target=run_thread,args=(5,)) t2 = threading.Thread(target=run_thread,args=(8,)) t1.start() t2.start() t1.join() t2.join() print(balance)
ThreadLocal
import threading #创建全局ThreadLocal对象: local_school = threading.local() def process_student(): #获取当前线程关联的student std = local_school.student print('hello %s (in %s)'%(std,threading.current_thread().name)) def process_thread(val): #绑定ThreadLocal的student local_school.student = val process_student() t1 = threading.Thread(target=process_thread,args=('alice',),name='Thread-A') t2 = threading.Thread(target=process_thread,args=('bob',),name='Thread-B') t1.start() t2.start() t1.join() t2.join()