对python多线程与global变量详解

yipeiwu_com6年前Python基础

今天早上起来写爬虫,基本框架已经搭好,添加多线程爬取功能时,发现出错:

比如在下载文件的url列表中加入200个url,开启50个线程。我的爬虫…竟然将50个url爬取并全部命名为0.html,也就是说,最后的下载结果,是有1个0.html(重复的覆盖了),还有1-150。下面是我的代码:

x = str(theguardian_globle.g)
 #x为给下载的文件命的名
 filePath = "E://wgetWeiBao//"+x+".html"
 try:
  wget.download(url,filePath)
  theguardian_globle.g+=1
  print x+" is downloading..."
 
 except:
  print "error!"
#这个是全局变量g的定义
global g
 
g = 0

后来终于发现问题:多线程+全局变量是个危险的组合,因为程序有多个线程在同时执行,多个线程同时操作全局变量,会引起混乱。在多线程中操作全局变量,应当给该操作加锁。

以下为修改后的代码:

函数:
 
def downLoad(url,num):
 x = str(num)
 filePath = "E://wgetWeiBao//"+x+".html"
 try:
  wget.download(url,filePath)
  print x+" is downloading..."
 
 except:
  print "error!"
多线程消费者_给操作全局变量的语句加锁
class Cosumer(threading.Thread):
 def run(self):
  print('%s:started' % threading.current_thread())
 
  while True:
   global gCondition
   gCondition.acquire()
   while q.empty()==True:
    gCondition.wait()
   url = q.get()
   num = theguardian_globle.g
   theguardian_globle.g+=1
   gCondition.release()
   downLoad(url,num)

大功告成!

以上这篇对python多线程与global变量详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python 绘制拟合曲线并加指定点标识的实现

python 绘制拟合曲线并加指定点标识的实现

python 绘制拟合曲线并加指定点标识 import os import numpy as np from scipy import log from scipy.optimiz...

python如何读取bin文件并下发串口

下面是实现代码 # coding:utf-8 import time, serial from struct import * import binascii file = ope...

Python的Flask站点中集成xhEditor文本编辑器的教程

Python的Flask站点中集成xhEditor文本编辑器的教程

xhEditor简介 xhEditor是一个基于jQuery开发的简单迷你并且高效的可视化HTML编辑器,基于网络访问并且兼容IE 6.0+, Firefox 3.0+, Opera 9...

Python+selenium实现截图图片并保存截取的图片

这篇文章介绍如何利用Selenium的方法进行截图,在测试过程中,是有必要截图,特别是遇到错误的时候进行截图。在selenium for Python中主要有三个截图方法,我们挑选其中最...

Python数组条件过滤filter函数使用示例

使用filter函数,实现一个条件判断函数即可。 比如想过滤掉字符串数组中某个敏感词,示范代码如下: #filter out some unwanted tags def pass...