1、python多线程
1 #encoding=utf-8 2 """ 3 python多线程,并非真正意义上的多线程 4 全局锁:在指定时间里,有且只有一个线程在运行 5 6 7 """ 8 import threading 9 import time 10 11 def test(p): 12 time.sleep(0.1) 13 print p 14 15 # a = threading.Thread(target=test) 16 # b = threading.Thread(target=test) 17 # a.start() 18 # b.start() 19 # 20 # a.join() 21 # b.join() 22 23 lst =[] 24 for i in xrange(0, 15): 25 th = threading.Thread(target=test, args=[i]) 26 lst.append(th) 27 28 for i in lst: 29 i.start() 30 31 32 for i in lst: 33 i.join() 34 print "primary thread end!!!"
2、python下的锁
1 #encoding=utf-8 2 3 """ 4 1、python全局锁:GLT 5 python多线程在任意时刻下只有一个线程在运行,它是线程安全的 6 """ 7 8 import threading 9 10 num = 0 11 def t(): 12 global num 13 num +=1 14 print num 15 16 for i in xrange(0, 10): 17 d = threading.Thread(target=t) 18 d.start() 19 20 21 import time 22 b_time = time.time() 23 _a = threading.Thread(target=t) 24 _b = threading.Thread(target=t) 25 _a.start() 26 _b.start() 27 28 _a.join() 29 _b.join() 30 31 print time.time()-b_time 32 33 """ 34 加锁:acquire() 35 解锁:release() 36 RLock()可重入锁 37 38 39 """ 40 import threading 41 mlock = threading.Lock() 42 #mlock = threading.RLock() 43 44 num_01 = 0 45 def a(): 46 global num_01 47 mlock.acquire() 48 num_01 += 1 49 mlock.release() 50 print num_01 51 52 for i in xrange(0, 10): 53 d = threading.Thread(target=a) 54 d.start() 55