对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
投稿

猜你喜欢

  • Git操作规范之tag的使用技巧详解

    2022-07-30 05:10:54
  • Python程序设计入门(3)数组的使用

    2023-07-20 07:11:15
  • django配置连接数据库及原生sql语句的使用方法

    2024-01-19 19:22:56
  • MySql学习心得之存储过程

    2024-01-14 19:57:08
  • 图神经网络GNN算法基本原理详解

    2023-08-08 23:53:53
  • python通过tcp发送xml报文的方法

    2021-02-18 08:34:25
  • nginx搭建基于python的web环境的实现步骤

    2023-07-27 07:06:49
  • Go语言错误处理异常捕获+异常抛出

    2024-05-22 10:14:08
  • python使用正则表达式替换匹配成功的组并输出替换的次数

    2022-04-05 06:35:05
  • 人工智能学习Pytorch教程Tensor基本操作示例详解

    2021-06-14 17:39:22
  • Python语音合成的项目实战(PyQt5+pyttsx3)

    2021-06-15 09:14:13
  • 对python插入数据库和生成插入sql的示例讲解

    2022-03-10 05:46:40
  • python如何编写类似nmap的扫描工具

    2022-05-09 15:19:44
  • Python3 中sorted() 函数的用法

    2021-09-29 04:00:55
  • keras实现theano和tensorflow训练的模型相互转换

    2023-04-18 05:49:26
  • python列表推导式操作解析

    2022-08-26 04:07:39
  • Python自动打印被调用函数变量名及对应值 

    2022-08-05 09:50:38
  • Python Map 函数的使用

    2023-09-02 06:27:17
  • PyQt5实现从主窗口打开子窗口的方法

    2023-01-14 11:06:11
  • pyecharts绘制时间轮播图柱形图+饼图+玫瑰图+折线图

    2022-01-18 13:19:47
  • asp之家 网络编程 m.aspxhome.com