python 8-1 如何使用多线程
使用标准库中的threading.Thread创建线程, 在每一个线程中下载并转换一只股票数据
首先python受限于GIL的缘故,多线程只适合IO包括网络IO,磁盘IO,密集型的任务,不适合计算密集型的任务
实现多线程一般有两种方式
第一种:直接将需要执行逻辑部分的函数赋值给target
t = Thread(target=handle,args=(1,))
t.start()
第二种:定义一个自己的类继承Thread,然后将逻辑函数放在run方法中执行
class MyThread(Thread):
def init(self,sid):
self(MyThread,self).init()
self.sid = sid
def run(self):
handle(self.sid)
t=MyThread(1)
t.start()
from threading import Thread
def handle(sid):
print “Download…%d”% sid
url=”http://table.finance.yahoo.com/table.csv?s=%s.sz”
url %=str(sid).rjust(6,’0’)
rf = download(url)
if rf is not None: continue
print ‘Convert to XML …(%d)’ % sid
fname = str(sid).rjust(6,’0’) + ‘.xml’
with open (fname,’wb’) as wf:
createXmlFromCsv(rf,wf)
t = Thread(target=handle,args=(1,))
t.start()
class MyThread(Thread):
def init(self,sid):
self(MyThread,self).init()
self.sid = sid
def run(self):
handle(self.sid)
t=MyThread(1)
t.start()
import csv
from xml.et