msyz999明仕亚洲官网python多线程中为什么要用for遍历统统线程然后顺次调用join?

#!/usr/bin/python
# -*- coding: UTF-8 -*-

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 runself:
        print "Starting " + self.name
        process_dataself.name, self.q
        print "Exiting " + self.name

def process_datathreadName, 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.sleep1

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

# 创立新线程
for tName in threadList:
    thread = myThreadthreadID, tName, workQueue
    thread.start
    threads.appendthread
    threadID += 1

# 添补行列步队
queueLock.acquire
for word in nameList:
    workQueue.putword
queueLock.release

# 等待行列步队清空
while not workQueue.empty:
    pass

# 告诉线程是时分加入
exitFlag = 1

# 等待统统线程完成
for t in threads:
    t.join
print "Exiting Main Thread"

这段代码中扫尾为什么要用

for t in threads:
    t.join

如许写呢?我试过把这两行代码注释,仿佛运转也很正常啊

假如主线程需求获取子线程的形状就join;注释失运转,那便是主线程不需求获取子线程形状了,固然也是可以正常运转的。

参考:https://docs.python.org/2/lib…

join 主要用于进程/线程之间的协同,其服从在于等待目标进程/线程实行终了。

在此,由于你的线程操纵很复杂,服从函数实行完成后线程就终了了。join与否就显得区别不大。

(看完/读完)这篇文章有何感想! msyz999明仕亚洲官网的分享…

发表评论

姓名 *
电子邮件 *
站点