Python代码的多线程改造

并行化处理已经成为了很多工程项目的需求。本文展示了如何使用threadpool模块(支持Python 3.x)将普通的Python程序多线程化。

import requests
import bs4
import time
import threadpool

# build data array
data = []
for e in range(10,20):
	data.append(str(e))


def print_now(request):
	s = str(request.requestID)
	print (s)
  
def crawling(link):
	request_link = "http://www.wandoujia.com/search?key=" + str(link) + "&source=search"
	response = requests.get(request_link)	
	# other code lines	

# set the thread number
pool = threadpool.ThreadPool(10)
# makeRequests(some_callable, list_of_args, callback)
reqs = threadpool.makeRequests(crawling, data, print_now)
# run
[pool.putRequest(req) for req in reqs]
pool.wait()


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值