2

I want only one Thread to be active, here is the algorithm:

def myfunction(update):
    if threading.activeCount >=1:
        # kill all previous threads
    while true:
        # some execution


while true:
    t = threading.Thread(myfunction, args=([update]))
    t.start()

so In here thread goes in Infinite loop in myfunction, so before starting new one i need to close previous one, please guide me

Hackaholic
  • 19,069
  • 5
  • 54
  • 72
  • did you check this out? https://docs.python.org/2/library/threading.html#threading.Thread.join, and for the fun of it: http://bit.ly/1wDBDd9 – miraculixx Dec 24 '14 at 01:22
  • @miraculixx i dont need to wait, i need to force thread to stop – Hackaholic Dec 24 '14 at 01:27
  • have a look here http://stackoverflow.com/questions/14482230/why-does-the-python-threading-thread-object-has-start-but-not-stop – Padraic Cunningham Dec 24 '14 at 01:35
  • @Hackaholic you can't force it to stop from the outside, other than conditioning the loop, I was going to add an answer to that end, but since the question has been marked duplicate... – miraculixx Dec 24 '14 at 12:09
  • @miraculixx the problem is that, the while loop in function goes in infinite loop, so when next thread comes, i need to stop previous loop – Hackaholic Dec 24 '14 at 16:11
  • @Hackaholic, try `while true and not stop_condition: ...`, then in your main thread before `t.start()` do `stop_condition = true` and `current_thread.wait(t)`. Not sure this works for you, you'd have to give more details on the actual problem you're trying to solve. – miraculixx Dec 25 '14 at 10:27

1 Answers1

2

You can't kill threads, your function has to return somehow. The trick, then, is to write your function in such a way that it knows when to stop what its doing and return. That's very context dependent of course. Its common to implement your code as a class that has a 'close' method that knows what to do. For instance,

  • if the thread is waiting on a subprocess, the close could kill the subprocess.

  • If the thread does a sleep, you could use an event instead - the close would set the event.

  • If your thread is waiting on a queue, you could have a special method that tells it to return.

tdelaney
  • 73,364
  • 6
  • 83
  • 116