1

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.

Ze Kotch
  • 51
  • 4

2 Answers2

2

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.

Community
  • 1
  • 1
Henrik
  • 4,254
  • 15
  • 28
  • In that case how could it be done ? Because if the first word is correct it keeps verifying the remaining words in the dicfile. I don't want to check each word in the dicfile one at a time in the view of increasing performance. – Ze Kotch Jul 12 '13 at 12:59
  • Should be able to send a friendly signal (not sigkill, sigterm, etc.) to ask them to shut down cleanly, no? – ajwood Jul 12 '13 at 13:05
0

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
sebdelsol
  • 1,045
  • 8
  • 15