python 线程、协程简单使用

来源:互联网 发布:c语言新建文件步骤 编辑:程序博客网 时间:2024/06/06 00:38

python简单线程并发示例:

import threadingimport timemutex = 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 timeimport threadpooldef worker(num):    time.sleep(1)    return "this is %d" % numdef callback(request, result):    print request.requestID, resultif __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 greenletdef 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 geventdef func1():    print "func1", 1    gevent.sleep(0) # check out into func2    print "func1", 2def func2():    print "func2", 1    gevent.sleep(0)    print "func2", 2if __name__ == '__main__':    gevent.joinall([        gevent.spawn(func1),        gevent.spawn(func2),    ])

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

原创粉丝点击