5

i've got this code, how can I stop func2 from func1? something like Thread(target = func1).stop() doesn't work

import threading
from threading import Thread

def func1():
    while True:
        print 'working 1'

def func2():
    while True:
        print 'Working2'

if __name__ == '__main__':
    Thread(target = func1).start()
    Thread(target = func2).start()

2 Answers2

0

It's better to ask your other thread to stop, using a message queue for instance.

import time
import threading
from threading import Thread
import Queue

q = Queue.Queue()

def func1():
    while True:
        try:
            item = q.get(True, 1)
            if item == 'quit':
                print 'quitting'
                break
        except:
            pass
        print 'working 1'

def func2():
    time.sleep(10)
    q.put("quit")
    while True:
        time.sleep(1)
        print 'Working2'

if __name__ == '__main__':
    Thread(target = func1).start()
    Thread(target = func2).start()
Pelle Nilsson
  • 970
  • 8
  • 10
  • 1
    But when i want for example use raw_input at the end of func1. Then func2 can't close func1. Is there any solution for this? – Kacper Serewis Apr 06 '16 at 10:27
0

You cannot tell a thread to stop, you have to make it return in its target function

from threading import Thread
import Queue

q = Queue.Queue()

def thread_func():
    while True:
        # checking if done
        try:
            item = q.get(False)
            if item == 'stop':
                break  # or return
        except Queue.Empty:
            pass
        print 'working 1'


def stop():
    q.put('stop')


if __name__ == '__main__':
    Thread(target=thread_func).start()

    # so some stuff
    ...
    stop()  # here you tell your thread to stop
            # it will stop the next time it passes at (checking if done)
Pedru
  • 1,430
  • 1
  • 14
  • 32