python多线程和协程开发入门上手

1 篇文章 0 订阅
1 篇文章 0 订阅

python多线程和协程开发入门上手

今天学习了一下python的多线程的基本知识,感觉随threading稍有些啰嗦但是,比起java的语法还是简洁了不少,由于python本身根据全局锁的设计,所以python的多线程其实本质上不是真正意义上的多线程,因为在无论多么细微的同一个时间点永远都只有一个线程在跑,也许是出于安全的角度才这样设计,不过依然可以大大提高效率。

threading入门例子

最简单的一个例子:

import threading

def test(s):
    print 
a=threading.Thread(target=test,args=[1])
b=threading.Thread(target=test,args=[2])
a.start()
b.start()mpt'''

开启10个线程

最简单的一个例子:

threadlist=[]
for i in range(10):
    tmp=threading.Thread(target=test,args=[i])
    tmp.start()
    threadlist.append(tmp)

[x.join() for x in threadlist]
print 'end!'

效率最白痴测试

效率测试:

# def a():
#     print 'a begin!'
#     time.sleep(2)
#     print 'a end!'
# def b():
#     print 'b begin'
#     time.sleep(2)
#     print 'b end'
# 
# tmptime=time.time()
# a()
# b()
# print 'tim1',time.time()-tmptime
# tmptime=time.time()
# t1=threading.Thread(target=a)
# t2=threading.Thread(target=b)
# t1.start()
# t2.start()
# t1.join()
# t2.join()
# print time.time()-tmptime

加锁和释放锁

最简单的一个例子:

money=500
mLock=threading.Lock()
def addmoney():
    global money
    mLock.acquire()
    for i in range(100):
        money+=1
    mLock.release()
threads=[]
for x in range(10):
    tmp=threading.Thread(addmoney())
    tmp.start()
    threads.append(tmp)

[t.join() for t in threads]

print money

多线程读取文件

最简单的一个例子:

#多线程读取文件或者list
mutex = threading.Lock()
fp = open('D:\\2016-04-01_hi27_ni.txt')

class Reader(threading.Thread):

    def __init__(self, num):
        threading.Thread.__init__(self)
        self.num = num

    def run(self):
        while True:
            with mutex:
                line = fp.readline()
                if len(line) == 0:
                    return
                print str(self.num)+'   '+line
            time.sleep(0.1)


if __name__ == '__main__':
    r1 = Reader(1)
    r2 = Reader(2)

    r1.start()
    r2.start()

    r1.join()
    r2.join()

非常好用的map

最简单的一个例子:

from multiprocessing.dummy import Pool as ThreadPool

urls = [
        'http://www.python.org',
        'http://www.python.org/about/',
        'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html',
        'http://www.python.org/doc/',
        'http://www.python.org/download/',
        'http://www.python.org/getit/',
        'http://www.python.org/community/',
        'https://wiki.python.org/moin/',
        'http://planet.python.org/',
        'https://wiki.python.org/moin/LocalUserGroups',
        'http://www.python.org/psf/',
        'http://docs.python.org/devguide/',
        'http://www.python.org/community/awards/'
        # etc..
        ]*100000

# Make the Pool of workers
pool = ThreadPool(4)
# Open the urls in their own threads
# and return the results
results = pool.map(lambda x:x[-3], urls)
print '\n'.join(results)
#close the pool and wait for the work to finish
pool.close()
pool.join()

下面是关于协程:
协程说白了就是两个函数相互配合,达到多线程的效果。
通过生成器来产生的,效率极高,比方说xrange就是这样实现的,只是在遍历的时候才会去生成,不用像range一样立刻生成一块内存,效率高。

next 和send(none)等价,第一次是启动, 执行该函数到yield处停止跳回代码。
a=yield b
那么调用next或者send(c)传过去的值就是a
而返回的的值就是b。
r1=c.send(b)那么把b传给对面函数的yield后,执行到下一个yield就会返回的值让r1接住。
r1=c.next()同样道理只是没有传递值.
c是对面的函数
对于编码人员来说协程是两个函数相互传递信息并配合。不是多线程,但能取得多线程的效果

入门级别例子

最简单的一个例子:

def product():
     for i in xrange(10):
         print 'I come to ' ,i
         yield i 

a=product()
[a.next()for x in range(5)]

斐波那契数列的写法

最简单的一个例子:

# fibonacci 不需要参数,因为可以无限下去
def fibonacci():
      a=1
      b=1
      yield a
      yield b 
      while True:
          a,b=b,a+b 
          yield b 

fib=fibonacci()

print [fib.next()for x in range(100)]

生产者和消费者问题

最简单的一个例子:

# fibonacci 不需要参数,因为可以无限下去
def consumer():
    r = ''
    while True:
        n = yield r
        if not n:
            return
        print('[CONSUMER] ←← Consuming %s...' % n)
        time.sleep(1)
        r = '200 OK'

def produce(c):
    # 1、首先调用c.next()启动生成器
    c.next()
    n = 0
    while n < 5:
        n = n + 1
        print('[PRODUCER] →→ Producing %s...' % n)
        # 2、然后,一旦生产了东西,通过c.send(n)切换到consumer执行;
        cr = c.send(n)
        # 4、produce拿到consumer处理的结果,继续生产下一条消息;
        print('[PRODUCER] Consumer return: %s' % cr)
    # 5、produce决定不生产了,通过c.close()关闭consumer,整个过程结束。
    c.close()

    # 6、整个流程无锁,由一个线程执行,produce和consumer协作完成任务,所以称为“协程”,而非线程的抢占式多任务。
c = consumer()
produce(c)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值