Reputation: 51
Hi I'm trying to allow simultaneous testing of multiple words but I'm facing troubles with multithreading! Is it possible to terminate all other threads if one succeeded? Maybe I don't understand threading correctly! Pretty confused! Here is my code:
def testPass(hash, dname):
dicFile = open(dname,'r')
for word in dicFile.readlines():
word = word.strip('\n')
t = Thread(target=verifyWord, args=(hash, word))
t.start()
return
so I want to do something like if one of the t succeeded exit the loop. I don't know how to handle this.
Upvotes: 1
Views: 302
Reputation: 1085
As suggested use a stop event that you regularly check in verifyWord, and set it when your task is done:
def verifyWord(hash,word,stopevent):
#for every chunk of your computation, check that stopEvent is not set
if not self.stopEvent.isSet():
#do a part of your computation
...
#When you're done
self.stopEvent.set()
Break out the for loop, when stopEvent has been set:
def testPass(hash, dname):
stopEvent = threading.Event()
dicFile = open(dname,'r')
for word in dicFile.readlines():
word = word.strip('\n')
t = Thread(target=verifyWord, args=(hash, word,stopEvent))
t.start()
if stopEvent.isSet():
break
Upvotes: 0
Reputation: 4314
Forcing threads to terminate abruptly (i.e. killing them) is generally not a good idea - bad things can happen from a synchronization point of view.
You can achieve what you want by having all your threads checking a flag on a regular basis, telling them to terminate ASAP (but in a safe way) if the flag is set.
This answer should get you going nicely.
Upvotes: 2