标签:
1、多进程,multiprocessing模块,
进程间的通信:Queue[队列],Pipes[管子]
2、多线程,
注意:线程公用变量,混乱
解决方法Lock:因为只有一个锁,所以当要执行统一个函数的时候,只有在解锁的前提下才能
执行。
balance = 0 lock = threading.Lock() def run_thread(n): for i in range(100000): # 先要获取锁: lock.acquire() try: # 放心地改吧: change_it(n) finally: # 改完了一定要释放锁: lock.release()
3、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(name): # 绑定ThreadLocal的student: local_school.student = name 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()
【Python】[进程和线程]多进程,多线程,ThreadLocal,进程VS.线程,分布式进程
标签:
原文地址:http://www.cnblogs.com/oiliu/p/4757137.html