入门
推荐使用多进程会更合理使用多核cpu,但是多个线程还是使用同一个单核cpu
python 使用的全局GIL代表在任意的时间里 有且只有一个线程在运行 线程是安全的
import threading
import time
def test(p):
time.sleep(0.001)
print p
ts = []
for i in xrange(0,15):
th = threading.Thread(target=test,args=[i])
th.start()
ts.append(th)
for i in ts:
i.join() //等待所有的线程执行完 再执行主线程
print "hoho,end!!!!!" //主线程
常用
import time
import threading
def a():
print 'a begin'
time.sleep(2)
print 'a end'
def b():
print 'b begin'
time.sleep(2)
print 'b end'
b_time = time.time()
_a = threading.Thread(target=a)
_b = threading.Thread(target=b)
_a.start()
_b.start()
_a.join()
_b.join()
print time.time() - b_time #代码完成时间 一般在2s钟多点
加锁 释放锁 lock,acquire release
import threading
mlock = threading.RLock()
num = 0
def a():
global num
mlock.acquire() #加锁
num += 1 #你要执行的代码
mlock.release() #释放锁
print num
for i in xrange(0,10):
d = threading.Thread(target=a)
d.start()
协程yield
def test():
x = yield '第一步' #第一次next 直接返回yield后面的值 剩下的的语句执行
print '第二步st %s, '%x #x的值必须使用send不然为None#第二次next从上次yield执行结束的地方开始
x = yield '第二步返回 %s,'%x
print '第三步st %s, '%x
x = yield
t = test()
print t.next()
#print t.next()
#print t.next()
print t.send('send传递')
print t.next()