python 多线程

入门

推荐使用多进程会更合理使用多核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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值