Python线程。当前线程()和callb

2024-03-28 19:11:02 发布

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

我有下面这个小线程测试代码。线程名称有时是执行者的名称有时是主线程的名称。根据3.7 Python doc 添加\u完成\u回调(fn) ... 添加的可调用项按添加顺序调用,并且总是在属于添加它们的进程的线程中调用。

为什么随机得到不同的线程名称?你知道吗

from concurrent.futures import ThreadPoolExecutor
import threading

def task(n):
    print(f'task - Thread: {threading.current_thread().name}')
    print("Processing {}".format(n))
    ttask()


def ttask():
    print(f'ttask - Thread: {threading.current_thread().name}')
    print("Processing ")


def taskDone(fn):
    print(f'taskDone - Thread: {threading.current_thread().name}')
    if fn.cancelled():
        print("Our {} Future has been cancelled".format(fn.arg))
    elif fn.done():
        print("Our Task has completed")


def secondTaskDone(fn):
    print(f'secondaTaskDone - Thread: {threading.current_thread().name}')
    print("I didn't think this would work")


def main():
    print("Starting ThreadPoolExecutor")
    print(f'Thread: {threading.current_thread().name}')
    with ThreadPoolExecutor(max_workers=3) as executor:
        print(f'Thread: {threading.current_thread().name}')
        future = executor.submit(task, (2))
        future.add_done_callback(taskDone)
        future.add_done_callback(secondTaskDone)

    print("All tasks complete")


if __name__ == '__main__':
    main()

输出是随机的:

输出1:

Starting ThreadPoolExecutor
Thread: MainThread
Thread: MainThread
task - Thread: ThreadPoolExecutor-0_0
Processing 2
ttask - Thread: ThreadPoolExecutor-0_0
Processing
taskDone - Thread: ThreadPoolExecutor-0_0
Our Task has completed
secondaTaskDone - Thread: ThreadPoolExecutor-0_0
I didn't think this would work
All tasks complete

输出2:

Starting ThreadPoolExecutor
Thread: MainThread
Thread: MainThread
task - Thread: ThreadPoolExecutor-0_0
Processing 2
ttask - Thread: ThreadPoolExecutor-0_0
Processing
taskDone - Thread: MainThread
Our Task has completed
secondaTaskDone - Thread: MainThread
I didn't think this would work
All tasks complete

Tags: nametaskdefcurrent线程threadfnprint