Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python线程。当前线程()和回调_Python_Multithreading - Fatal编程技术网

Python线程。当前线程()和回调

Python线程。当前线程()和回调,python,multithreading,Python,Multithreading,我有下面这个小线程测试代码。线程名称有时是执行器的名称,有时是主线程的名称。根据3.7 Python文档 添加完成的回调(fn) ... 添加的可调用项按添加顺序调用,并且始终在属于添加它们的进程的线程中调用 为什么随机获得不同的线程名称 from concurrent.futures import ThreadPoolExecutor import threading def task(n): print(f'task - Thread: {threading.current_thr

我有下面这个小线程测试代码。线程名称有时是执行器的名称,有时是主线程的名称。根据3.7 Python文档 添加完成的回调(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

本主题回答了这个问题。谢谢@dano。

为ttask()添加了0.2s延迟,回调始终在“ThreadPoolExecutor-0\u 0”中运行

此问题可与上述主题重复