进程案例
import multiprocessing
import time
import os
def getdata(data):
data1,data2=data
print os.getpid(),"start"
#time.sleep(3)
print os.getpid(), "end"
return data1*data1,data2
if __name__=="__main__":
mylist=[(x,x+1) for x in range(100)]
pool=multiprocessing.Pool(processes=5) #进程池,最大执行4个
pool_outputs=pool.map(getdata,mylist) #抓取进程池的所有执行结果
pool.close() #关闭进程池
pool.join() #等待进程干完
print pool_outputs
协程案例
import gevent
import gevent.monkey
import urllib2
gevent.monkey.patch_all()#自动切换
def download(url):
print "start",url
data=urllib2.urlopen(url).read()
print "length",len(data),url
gevent.joinall([
gevent.spawn(download,"http://www.baidu.com"),
gevent.spawn(download,"http://www.163.com"),
gevent.spawn(download,"http://www.qq.com"),
gevent.spawn(download,"http://www.sina.com"),
])
线程案例
import threading
import time
def myThread(name):
with sep:
for i in range(10):
time.sleep(1)
print name,str(i),threading.current_thread().name #线程名字
sep=threading.Semaphore(2)
threadlist=[]
for name in ["a","b","c","d","e"]:
mythd=threading.Thread(target=myThread,args=(name,))
mythd.start()
threadlist.append(mythd)#循环加入到列表
for thread in threadlist:
thread.join()