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)

猜你喜欢

转载自www.cnblogs.com/benchdog/p/9185443.html