在多线程Python代码中停止线程

时间:2018-01-24 20:30:41

标签: python multithreading

我正在使用python中的多线程,我无法实现停止单个线程。代码如下。我怎样才能实现这一目标?感谢...

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()

执行此代码后,线程必须处于活动状态且仍在运行该函数,但所有线程都会停止。

2 个答案:

答案 0 :(得分:3)

显然,您希望线程<?php include_once 'includes/db_connect.php'; secure_session_start(); mysqli_select_db("DATABASE", $mysqli); $sql="INSERT INTO table (id, member_id, description) VALUES ('1','test', 'test')"; if (!mysqli_query($sql,$mysqli)) { die('Error: ' . mysqli_error()); } mysqli_close($con) ?> 不应该停止,因为您没有调用a。但是,您还有一个类范围属性a.stop()

stopped

因此,class MyThread(threading.Thread): def stop(self): self.stopped = True print ("working") # !! this is a class level attribute !! stopped=True MyThread.stopped。当您使用True询问MyThread属性stopped的实例时,它会:

  • 首先检查实例;
  • 上是否存在属性self.stopped
  • else检查类型stopped
  • 上是否存在该属性

因此,在您的情况下,MyThread 总是 MyThread().stopped

答案 1 :(得分:0)

我弄明白了解决方案并想分享。

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