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),
])