1、python多线程
#encoding=utf-8
"""
python多线程,并非真正意义上的多线程
全局锁:在指定时间里,有且只有一个线程在运行
"""
import threading
import time def test(p):
time.sleep(0.1)
print p # a = threading.Thread(target=test)
# b = threading.Thread(target=test)
# a.start()
# b.start()
#
# a.join()
# b.join() lst =[]
for i in xrange(0, 15):
th = threading.Thread(target=test, args=[i])
lst.append(th) for i in lst:
i.start() for i in lst:
i.join()
print "primary thread end!!!"
2、python下的锁
#encoding=utf-8 """
1、python全局锁:GLT
python多线程在任意时刻下只有一个线程在运行,它是线程安全的
""" import threading num = 0
def t():
global num
num +=1
print num for i in xrange(0, 10):
d = threading.Thread(target=t)
d.start() import time
b_time = time.time()
_a = threading.Thread(target=t)
_b = threading.Thread(target=t)
_a.start()
_b.start() _a.join()
_b.join() print time.time()-b_time """
加锁:acquire()
解锁:release()
RLock()可重入锁
"""
import threading
mlock = threading.Lock()
#mlock = threading.RLock() num_01 = 0
def a():
global num_01
mlock.acquire()
num_01 += 1
mlock.release()
print num_01 for i in xrange(0, 10):
d = threading.Thread(target=a)
d.start()