python多线程与global变量
2017-02-17 10:45
330 查看
今天早上起来写爬虫,基本框架已经搭好,添加多线程爬取功能时,发现出错:
比如在下载文件的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 局部变量和全局变量 global
- python中必须使用global声明全局变量的情况
- python 使用全局变量 global
- python global语句 变量作用域
- 『Python』 多线程 共享变量的实现
- python语法31[变量的作用域+global]
- 实例讲解Python中global语句下全局变量的值的修改
- 为什么python在函数中修改"字典型全局变量"不需要global
- Python多线程下的变量问题
- Python多线程下的全局变量、局部变量
- Python全局变量的隐藏“窍门”(CONSTANT,global)
- 飘逸的python - 为什么修改全局的dict变量不用global关键字
- python main函数中变量默认为global variable
- [Python学习] 专题六.局部变量、全局变量global、导入模块变量
- python语法31[变量的作用域+global]
- python 局部变量和全局变量 global
- Python基础学习篇——Global全局变量的使用
- 练习生产者与消费者-PYTHON多线程中的条件变量同步-Queue
- python 全局变量global