Python多线程执行失败

问题描述

Python多线程执行失败

我使用python编程实现查找某根目录下所有重复文件的功能,新手小白。
但是通过单步调试后,发现thread2.start()好像完全没有执行,直接就跳出循环了。
请高手看看~

解决方案

附代码

-*- coding: utf-8 -*-

import threading
import os
import os.path
import sys
import hashlib

def findFile1(rootPath, fileSeq, delSeq):
dirs = os.listdir(rootPath) #list the directories under the root path
for dir in dirs[0:len(dirs) // 2]: #traversal all the directories
path = rootPath + os.sep + dir #complete the path of current file
if os.path.isdir(path):
findFile1(path, fileSeq, delSeq) #if current file is a directory, recursive the function
else:
md5Check(path, fileSeq, delSeq) #if not a directory, check the md5

def findFile2(rootPath, fileSeq, delSeq):
# type: (object, object, object) -> object
dirs = os.listdir(rootPath) #list the directories under the root path
for dir in dirs[len(dirs) // 2 + 1:len(dirs)]: #traversal all the directories
path = rootPath + os.sep + dir #complete the path of current file
if os.path.isdir(path):
findFile2(path, fileSeq, delSeq) #if current file is a directory, recursive the function
else:
md5Check(path, fileSeq, delSeq)

def md5Check(path, fileSeq, delSeq):
f = file(path, 'rb') #open the file with 'read-only' and 'binary'
md5obj = hashlib.md5()
md5obj.update(f.read()) #calculate the md5
if md5obj.hexdigest() in fileSeq:
mutex1.acquire()
delSeq.append(path)
mutex1.release() #if md5 of current file is in the fileSeq, put the file path into the delSeq
else:
mutex2.acquire()
fileSeq.append(md5obj.hexdigest()) #if not in the fileSeq, put the md5 into the fileSeq
mutex2.release()

f.close() #close the file

def delList(delSeq):
print 'These files are waiting to be removed:'
for delFile in delSeq:
print delFile #list the file path in the delSeq

class myThread1 (threading.Thread):
def init(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
def run(self):
print "Starting " + self.name
# 获得锁,成功获得锁定后返回True
# 可选的timeout参数不填时将一直阻塞直到获得锁定
# 否则超时后将返回False
findFile1(rootPath, fileSeq, delSeq)
# 释放锁

class myThread2 (threading.Thread):
def init(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
def run(self):
print "Starting " + self.name
findFile2(rootPath, fileSeq, delSeq)
# 释放锁

mutex1 = threading.Lock()
mutex2 = threading.Lock()
threads = []

创建新线程

thread1 = myThread1(1, "Thread-1")
thread2 = myThread2(2, "Thread-2")

global fileSeq
fileSeq = []
global delSeq
delSeq = []

while True:
if len(sys.argv) == 1:
global rootPath
rootPath = raw_input('Enter the root path: ') #one parameter means no parameter, ask the root path
else:
rootPath = sys.argv[1] #or get the second parameter as the root path
try:
# 开启新线程
thread1.start()
thread2.start()
#try if the root path is valid
except(OSError):
print 'The root path is invalid. Please enter again. '
del sys.argv[1:]
continue #catch the except and delete all invalid parameters
break

if len(delSeq) == 0 :
print 'No duplicate file was found! ' #if no files in delSeq, exit
else:
delList(delSeq) #or list the delSeq
while True:
answer = raw_input('Would you want to remove these files? Please answer yes(y) or no(n): ')
answer.lower
if answer in ('yes', 'y'): #if "yes"
for delFile in delSeq:
try:
os.remove(delFile) #remove all files in delSeq
except(OSError):
print 'Warning! "%s" is not existed! ' % delFile
continue #ignore the files witch are not existed
print 'All duplicate files have been removed! '
break
elif answer in ('no', 'n'):
print 'Process has exited without any change! '
break #if "no", do nothing
else:
print 'Please enter yes(y) or no(n). '
sys.exit()

添加线程到线程列表

threads.append(thread1)
threads.append(thread2)

等待所有线程完成

for t in threads:
t.join()
print "Exiting Main Thread"

时间: 2024-07-28 16:41:22

Python多线程执行失败的相关文章

Python多线程编程学习

Python 提供了几个用于多线程编程的模块,包括thread, threading 和Queue 等.thread 和threading 模块允许程序员创建和管理线程.thread 模块提供了基本的线程和锁的支持,而threading提供了更高级别,功能更强的线程管理的功能.Queue 模块允许用户创建一个可以用于多个线程之间共享数据的队列数据结构. 注意:避免使用thread模块,因为它不支持守护线程.当主线程退出时,所有的子线程不论它们是否还在工作,都会被强行退出. 下面重点说说threa

浅析Python多线程下的变量问题

  这篇文章主要介绍了Python多线程下的变量问题,由于GIL的存在,Python的多线程编程问题一直是开发者中的热点话题,需要的朋友可以参考下 在多线程环境下,每个线程都有自己的数据.一个线程使用自己的局部变量比使用全局变量好,因为局部变量只有线程自己能看见,不会影响其他线程,而全局变量的修改必须加锁. 但是局部变量也有问题,就是在函数调用的时候,传递起来很麻烦: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 def process_student(name): std =

python多线程用法实例详解_python

本文实例分析了python多线程用法.分享给大家供大家参考.具体如下: 今天在学习尝试学习python多线程的时候,突然发现自己一直对super的用法不是很清楚,所以先总结一些遇到的问题.当我尝试编写下面的代码的时候: 复制代码 代码如下: class A():     def __init__( self ):         print "A" class B( A ):     def __init__( self ):         super( B, self ).__in

mysql-python 脚本中sql语句执行失败的问题

问题描述 python 脚本中sql语句执行失败的问题 如题,一句sql语句,在mysql命令行下可以执行并且有结果,但是,放在一段python脚本里, db.cursor.excute(sql)怎么都是0,这是怎么回事,求破 (我用的pymysql包做数据库连接池,autocommit为Ture) 解决方案 SQL语句中的执行时间问题执行SQL语句脚本文件解决存储过程中SQL字符串语句执行引入参数的问题 解决方案二: 先打印一下python的sql语句,看是否有区别

python多线程编程方式分析示例详解_python

在Python多线程中如何创建一个线程对象如果你要创建一个线程对象,很简单,只要你的类继承threading.Thread,然后在__init__里首先调用threading.Thread的__init__方法即可 复制代码 代码如下: import threading  class mythread(threading.Thread):  def __init__(self, threadname):  threading.Thread.__init__(self, name = thread

【Python之旅】第六篇(三):Python多线程及其使用方法

1.Python中的多线程     执行一个程序,即在操作系统中开启了一个进程,在某一时刻,一个CPU内核只能进行一个进程的任务,现在的计算机所说的多进程/多任务其实是通过加快CPU的执行速度来实现的,因为一个CPU每秒能执行上亿次的计算,能够对进程进行很多次切换,所以在人为可以感知的时间里,看上去,计算机确实是在同时执行多个程序,即同时处理多个进程.     一个进程中可以包含有多个线程,这多个线程为实现该进程的某个主要功能而运行着,多个线程可以进行串行工作,也可以并发同时进行工作,显然后者可

【Python之旅】第六篇(四):Python多线程锁

  在多线程程序执行过程中,为什么需要给一些线程加锁以及如何加锁,下面就来说一说. 1.给线程加锁的原因     我们知道,不同进程之间的内存空间数据是不能够共享的,试想一下,如果可以随意共享,谈何安全?但是一个进程中的多个线程是可以共享这个进程的内存空间中的数据的,比如多个线程可以同时调用某一内存空间中的某些数据(只是调用,没有做修改).     试想一下,在某一进程中,内存空间中存有一个变量对象的值为num=8,假如某一时刻有多个线程需要同时使用这个对象,出于这些线程要实现不同功能的需要,线

python 多线程就这么简单

多线程和多进程是什么自行google补脑 对于python 多线程的理解,我花了很长时间,搜索的大部份文章都不够通俗易懂.所以,这里力图用简单的例子,让你对多线程有个初步的认识.   单线程   在好些年前的MS-DOS时代,操作系统处理问题都是单任务的,我想做听音乐和看电影两件事儿,那么一定要先排一下顺序. (好吧!我们不纠结在DOS时代是否有听音乐和看影的应用.^_^) from time import ctime,sleep def music(): for i in range(2):

python多线程编程

Python多线程编程中常用方法: 1.join()方法:如果一个线程或者在函数执行的过程中调用另一个线程,并且希望待其完成操作后才能执行,那么在调用线程的时就可以使用被调线程的join方法join([timeout]) timeout:可选参数,线程运行的最长时间 2.isAlive()方法:查看线程是否还在运行 3.getName()方法:获得线程名 4.setDaemon()方法:主线程退出时,需要子线程随主线程退出,则设置子线程的setDaemon() Python线程同步: (1)Th