Python线程序列

时间:2016-11-22 21:27:41

标签: python python-multithreading

这是我为测试Python的线程序列而运行的示例程序

import threading
import time
import logging
import random

logging.basicConfig(level=logging.DEBUG,
        format = '%(asctime)s (%(threadName)-10s) %(message)s')

def worker():
        t = threading.currentThread()
        pause = random.randint(1,10)
        logging.debug('sleeping %s', pause)
        time.sleep(pause)
        logging.debug('ending sleep')
        return

for i in range(3):
        t = threading.Thread(target=worker,name='t%s'%i)
        t.setDaemon(True)
        t.start()

main_thread = threading.currentThread()
for t in threading.enumerate():
        if t is main_thread:
                continue
        logging.debug('joining %s', t.getName())
        t.join()

以下是程序运行的输出:

2016-11-22 12:59:12,052 (t0        ) sleeping 3
2016-11-22 12:59:12,052 (t1        ) sleeping 3
2016-11-22 12:59:12,052 (t2        ) sleeping 8
2016-11-22 12:59:12,052 (MainThread) joining t0
2016-11-22 12:59:15,055 (t0        ) ending sleep
2016-11-22 12:59:15,056 (MainThread) joining t2
2016-11-22 12:59:15,056 (t1        ) ending sleep
2016-11-22 12:59:20,054 (t2        ) ending sleep
2016-11-22 12:59:20,054 (MainThread) joining t1

请注意,加入顺序与枚举列表顺序或时序顺序不一致。主线程的连接顺序应该调用t0 - > t1 - > t2线程序列,但它是 - > t2 - > T1

这里发生了什么?

1 个答案:

答案 0 :(得分:0)

git difftool没有说明它枚举线程的顺序。查看源代码,将在两个threading.enumerate() dict_active中跟踪线索。枚举时,枚举这些词典的键,并且未定义它们的顺序。

以这种方式加入线程是有风险的。您考虑了主线程,但如果您为自己的目的导入了使用后台线程的模块,该怎么办?相反,请保留自己的列表

_limbo

输出

import threading
import time
import logging
import random

logging.basicConfig(level=logging.DEBUG,
        format = '%(asctime)s (%(threadName)-10s) %(message)s')

def worker():
        t = threading.currentThread()
        pause = random.randint(1,10)
        logging.debug('sleeping %s', pause)
        time.sleep(pause)
        logging.debug('ending sleep')
        return

threads = []

for i in range(3):
        t = threading.Thread(target=worker,name='t%s'%i)
        t.setDaemon(True)
        t.start()
        threads.append(t)

for t in threads:
        logging.debug('joining %s', t.getName())
        t.join()