我应该一直用吗线程.Thread.join()

2024-03-29 06:01:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我从here学习了多线程,并使用最后一个示例作为所有多线程应用程序的模板。代码如下:

#!/usr/bin/python

import Queue
import threading
import time

exitFlag = 0

class myThread (threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q
    def run(self):
        print "Starting " + self.name
        process_data(self.name, self.q)
        print "Exiting " + self.name

def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            queueLock.release()
            print "%s processing %s" % (threadName, data)
        else:
            queueLock.release()
        time.sleep(1)

threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = Queue.Queue(10)
threads = []
threadID = 1

# Create new threads
for tName in threadList:
    thread = myThread(threadID, tName, workQueue)
    thread.start()
    threads.append(thread)
    threadID += 1

# Fill the queue
queueLock.acquire()
for word in nameList:
    workQueue.put(word)
queueLock.release()

# Wait for queue to empty
while not workQueue.empty():
    pass

# Notify threads it's time to exit
exitFlag = 1

#here is where i do my write to file, the last operation**

# Wait for all threads to complete
for t in threads:
    t.join()
#print "Exiting Main Thread"

如您所见,此示例在所有线程上使用t.join()来等待它们完成。我的实际版本是超长和大型项目,但这不是重点。我只是想知道在不需要使用join()时是否有特殊情况?在


Tags: tonameimportselffordatatimequeue
1条回答
网友
1楼 · 发布于 2024-03-29 06:01:01

I'm just wondering if there are any special cases when join() doesn't need to be used?

一个明显的例子是当某个另一个线程(您正在连接的)正在连接该线程,所以您不必这样做,但您可能不需要被告知该线程。:)

首先,^{}线程不需要连接(通常也不应该连接)。你可以放弃它们,当你的主线程退出时,它们会在某个时刻突然终止。(当然,确保不要在守护进程线程中做任何危险的事情,比如覆盖文件。)

第二,如果你没有join你的(正常的,非守护进程)线程,它实际上并没有记录到底会发生什么。您的主线程可能以任意顺序等待所有线程,或者当线程在后台继续工作时,它可能退出并返回shell,或者它可能会杀死它们。但是如果你因为某种原因根本不在乎其中哪一种情况发生,那就不要join。在

第三,在许多平台上,很好地定义了将要发生的事情(通常,这是“它们都以某种任意的顺序得到{}ed”)。例如,如果您正在编写一个只需在Red Hat Linux下的CPython上运行的程序,并且您确信在Red Hat Linux下的CPython中会发生什么,并且您的程序结构使您很难跟踪线程,那么不join而不是重新定义整个程序是合理的。在

最后,不应该连接虚拟线程。但是如果您有虚拟线程,并且不知道自己有虚拟线程,那么您的问题将比join更大。在

相关问题 更多 >