python-多线程+协程

GIL锁的存在,使python实现不了通过多核来完成多线程并行,如果想让python利用多核,只能通过开多进程来实现。所以python适合执行计算密集型任务。

资源抢占式:线程、进程

协程:协作式---->即非抢占式程序,关键词:yield生成器,主要解决的也是IO操作,但不能利用多核(没有多进程的情况下)

多进程+协程:解决进程并发

重温yield生成器:

def f():
    print("ok")
    s=yield 6
    print(s)
    print("ok2")
    yield


gen=f()
# print(gen)

# next(gen)
RET=gen.__next__()
print(RET)

# next(gen)
gen.send(5)

 协程的优势:1)没有切换的消耗(涉及到IO操作会自动切换);2)没有锁的概念,本质上就是一个线程

利用协程+多线程可实现并发。

时间驱动编程思想:一种编程范式。

以下是协程实现:

# from greenlet import greenlet
#
# def test1():
#     print(12)
#     gr2.switch()
#     print(34)
# def test2():
#     print(56)
#     gr1.switch()
#     print(78)
#     gr1.switch()
#
# gr1 = greenlet(test1)
# gr2 = greenlet(test2)
# gr2.switch()

 

import gevent
import requests,time
start=time.time()
def f(url):
    print('GET: %s' % url)
    resp =requests.get(url)
    data = resp.text
    print('%d bytes received from %s.' % (len(data), url))

#f('https://www.python.org/')
#f('https://www.yahoo.com/')
#f('https://www.baidu.com/')
#f('https://www.sina.com.cn/')
#f("http://www.xiaohuar.com/hua/")

gevent.joinall([         gevent.spawn(f, 'https://www.python.org/'),         gevent.spawn(f, 'https://www.yahoo.com/'),         gevent.spawn(f, 'https://www.baidu.com/'),         gevent.spawn(f, 'https://www.sina.com.cn/'),         gevent.spawn(f, 'http://www.xiaohuar.com/hua/'), ])


print("cost time:",time.time()-start)

 

转载于:https://www.cnblogs.com/benchdog/p/9185443.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值