对python多线程与global变量详解

作者:hsj_csdn 时间:2021-03-05 20:34:48 

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

比如在下载文件的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)

大功告成!

来源:https://blog.csdn.net/hsj_csdn/article/details/55505475

标签:python,多线程,global
0
投稿

猜你喜欢

  • ASP编程入门进阶教程

    2008-06-29 18:00:00
  • PHPStudy下如何为Apache安装SSL证书的方法步骤

    2023-11-14 18:57:09
  • 有关缓存 Cache 的随想

    2008-06-09 14:25:00
  • JS不同加载方式下的window.onload

    2009-05-21 18:09:00
  • Python 私有化操作实例分析

    2022-11-06 05:44:42
  • python GUI编程(Tkinter) 创建子窗口及在窗口上用图片绘图实例

    2021-12-21 19:37:29
  • Python正则表达re模块之findall()函数详解

    2021-04-20 05:00:16
  • python十进制转二进制的详解

    2023-06-07 23:39:33
  • python文件比较示例分享

    2023-03-17 21:10:23
  • Python configparser模块操作代码实例

    2021-11-05 18:48:08
  • ASP用户登录验证代码

    2008-05-15 12:49:00
  • 详解Python异常处理中的Finally else的功能

    2023-08-19 01:01:20
  • 一次MySQL性能优化实战

    2009-03-09 15:01:00
  • 定位后无法选择容器内容解决方案

    2008-07-28 13:14:00
  • Python 面向对象之封装、继承、多态操作实例分析

    2021-04-09 10:03:54
  • python3实现163邮箱SMTP发送邮件

    2021-02-28 07:59:19
  • Pytorch自动求导函数详解流程以及与TensorFlow搭建网络的对比

    2023-07-08 18:44:37
  • Python中GIL的使用详解

    2022-02-08 13:36:30
  • Python基于pygame实现的font游戏字体(附源码)

    2021-04-16 05:06:17
  • Python实现emoji表情的简单方法

    2023-07-09 13:10:22
  • asp之家 网络编程 m.aspxhome.com