python 线程、协程简单使用

python简单线程并发示例:

import threading
import time

mutex = threading.Lock()

def worker(num):
    time.sleep(1)
    mutex.acquire()
    print "this is ",num
    mutex.release()

if __name__ == '__main__':
    for i in range(10):
        th = threading.Thread(target=worker, args=(i,), name="thread %d" % i)
        th.start()

python 线程池简单使用:

import time

import threadpool


def worker(num):
    time.sleep(1)
    return "this is %d" % num


def callback(request, result):
    print request.requestID, result


if __name__ == '__main__':
    pool = threadpool.ThreadPool(10)
    for i in range(10):
        reqlist = threadpool.makeRequests(worker, (i,), callback)
        for req in reqlist:
            pool.putRequest(req)
    pool.wait()

简单协程应用:

from greenlet import greenlet


def func1():
    print "func1", 1
    gr2.switch()
    print "func1", 2
    gr2.switch()


def func2():
    print "func2", 1
    gr1.switch()
    print "func2", 2
    gr1.switch()


if __name__ == '__main__':
    gr1 = greenlet(func1)
    gr2 = greenlet(func2)
    gr1.switch()

gevent

import gevent


def func1():
    print "func1", 1
    gevent.sleep(0) # check out into func2
    print "func1", 2


def func2():
    print "func2", 1
    gevent.sleep(0)
    print "func2", 2


if __name__ == '__main__':
    gevent.joinall([
        gevent.spawn(func1),
        gevent.spawn(func2),
    ])

参考链接:http://www.cnblogs.com/suoning/p/5599030.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值