多线程:
Python的标准库提供了两个模块:thread和threading,thread是低级模块,threading是高级模块,对thread进行了封装。绝大多数情况下,我们只需要使用threading这个高级模块。
一、启动一个线程就是把一个函数传入并创建Thread实例,然后调用start()开始执行:
一个例子:
import time,threading def loop(): print 'thread %s is running...' % threading.current_thread().name for n in range(0,5): print 'thread %s ----> %s' % (threading.current_thread().name, n) time.sleep(1) print 'thread %s end...' % threading.current_thread().name print 'thread %s is running...' % threading.current_thread().name t0 = threading.Thread(target = loop, name=('Thread%s' % 0)) t1 = threading.Thread(target = loop, name=('Thread%s' % 1)) t0.start() t1.start() t0.join() t1.join() print 'thread %s end...' % threading.current_thread().name
二、一个没有同步锁机制的多线程,最终的balance数值会不是0
import time, threading balance = 0 def change_it(n): #xian chun hou qu, jie guo ying gai shi 0 global balance balance = balance + n balance = balance - n def run_thread(n): for i in range(10000): change_it(n) t0 = threading.Thread(target=run_thread, args=(57,)) t1 = threading.Thread(target=run_thread, args=(86,)) t0.start() t1.start() t0.join() t1.join() print balance
三、同步锁机制
import time, threading balance = 0 def change_it(n): #xian chun hou qu, jie guo ying gai shi 0 global balance balance = balance + n balance = balance - n ##创建一个锁就是通过threading.Lock()来实现 lock = threading.Lock() def run_thread(n): for i in range(10000): lock.acquire() try: change_it(n) finally: lock.release() t0 = threading.Thread(target=run_thread, args=(57,)) t1 = threading.Thread(target=run_thread, args=(86,)) t0.start() t1.start() t0.join() t1.join() print balance