0

I am working on multithreading in python i could not achieve to stop individual threads. The code is below. How can i achieve this? Thanks...

from threading import Thread
import threading
import time


class MyThread(threading.Thread):
    def stop(self):
        self.stopped = True
        print ("working")
    stopped=True


def func(argument):
    t = threading.current_thread()
    while not t.stopped:
        print(argument)
        time.sleep(0.5)


a = MyThread(target=func,args=("1",))
b = MyThread(target=func,args=("2",))
c = MyThread(target=func,args=("3",))
d = MyThread(target=func,args=("4",))
a.daemon = True
b.daemon = True
c.daemon = True
d.daemon = True
a.start()
b.start()
c.start()
d.start()

time.sleep(3)
b.stop()
c.stop()
d.stop()

After execution of this code, a thread must be alive and still running the function but all of the threads stop.

2 Answers 2

3

Clearly you expect that thread a should not stop as you have not called a.stop(). However, you have a class scoped attribute stopped as well:

class MyThread(threading.Thread):
    def stop(self):
        self.stopped = True
        print ("working")

    # !! this is a class level attribute !!
    stopped=True

Thus, MyThread.stopped is True. When you ask an instance of MyThread for the stopped attribute using self.stopped it will:

  • first check if the attribute stopped exists on the instance;
  • else check if the attribute exists on the type MyThread

Thus in your case, MyThread().stopped is always True

Sign up to request clarification or add additional context in comments.

2 Comments

then, which method should i use?
I think you want to initialize stopped = False in your class definition.
0

I figure it out the solution and wanted to share.

from threading import Thread
import threading
import time


class MyThread(threading.Thread):
    stop = False


def func(argument):
    t = threading.current_thread()
    while True:
        if not t.stop:
            print(argument)
            time.sleep(0.5)


a = MyThread(target=func,args=("1",))
b = MyThread(target=func,args=("2",))
c = MyThread(target=func,args=("3",))
d = MyThread(target=func,args=("4",))
a.start()
b.start()
c.start()
d.start()
time.sleep(3)
b.stop = True
c.stop = True
d.stop = True
time.sleep(3)
b.stop = False

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.