Python:确保线程未在后台运行

时间:2015-11-20 17:42:53

标签: python multithreading parallel-processing

我正在阅读一本关于线程的书中的例子,这是他们给出的例子:

## To use threads you need import Thread using the following code:
from threading import Thread

##Also we use the sleep function to make the thread "sleep" 
from time import sleep

## To create a thread in Python you'll want to make your class work as a thread.
## For this, you should subclass your class from the Thread class
class CookBook(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.message = "Hello Parallel Python CookBook!!\n"

##this method thod prints only the message 
    def print_message(self):
        print (self.message)

##The run method prints ten times the message 
    def run(self):
        print ("Thread Starting\n")
        x=0
        while (x < 10):
            self.print_message()
            sleep(2)
            x += 1
        print ("Thread Ended\n")


#start the main process
print ("Process Started")

# create an instance of the HelloWorld class
hello_Python = CookBook()

# print the message...starting the thread
hello_Python.start()

#end the main process
print ("Process Ended")

#create an instance of the HelloWorld class
hello_Python = CookBook()

#print the message...starting the thread
hello_Python.start()

#end the main process
print ("Process Ended")

这是第一章的第一个例子,在本章的最后,作者说要确保你没有在后台运行任何线程,这是糟糕的编程。

问题:

根据我的例子,你如何正确验证没有线程在后台运行?

1 个答案:

答案 0 :(得分:0)

根据您的需要,有两种方式:

  1. 使用join()作为评论建议。

  2. 设置线程守护程序线程,这意味着调用Thread.__init__(self, daemon=True)。当您的主线程退出时,您创建的其他线程也会自动退出,因此您不必担心它们在后台运行。