python 8-1 如何使用多线程,Thread创建线程,执行函数赋值给target//类+函数放在run方法中执行

本文介绍了Python中使用多线程的两种方式:通过`Thread`直接指定`target`函数和创建自定义线程类继承`Thread`并在`run`方法中执行任务。示例中展示了如何下载并转换股票数据,强调了Python的GIL限制,多线程更适合IO密集型任务而非计算密集型任务。
摘要由CSDN通过智能技术生成

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值