首页 > 解决方案 > 在python中使用许多函数参数进行线程化

问题描述

我有一个函数,它接受字符串类型的多个参数(* args)。线程如何处理每个接收到的参数。以下是我的处理方式:

def functionA(x):
    print(x)

def functionB(*args):
    for ar in args:
        th = threading.Thread(target=functionA, args=(ar, ))
        th.start()

但它不起作用。帮我。

标签: pythonpython-3.xfunctionargumentspython-multithreading

解决方案


正如评论中提到的,您的代码工作正常,增加了一些延迟以functionA显示当时所有线程都已启动:

import threading
import time
from datetime import datetime


def functionA(x, y):
    dte = datetime.utcnow()
    print(f"""Starting Thread {x:02} at: {dte:%Y-%m-%d %H:%M:%S}.{"{:03d}".format(dte.microsecond // 1000)}""")
    time.sleep(y)
    print(x)
    dte = datetime.utcnow()
    print(f"""Stopping Thread {x:02} at: {dte:%Y-%m-%d %H:%M:%S}.{"{:03d}".format(dte.microsecond // 1000)}""")

def functionB(*args):
    for i, ar in enumerate(args):
        th = threading.Thread(target=functionA, args=(ar, len(args)-i, ))
        th.start()


functionB(1,2,3,4,5,6,7,8,9,10)

出去:

Starting Thread 01 at: 2020-11-22 15:01:43.308
Starting Thread 02 at: 2020-11-22 15:01:43.308
Starting Thread 03 at: 2020-11-22 15:01:43.308
Starting Thread 04 at: 2020-11-22 15:01:43.308
Starting Thread 05 at: 2020-11-22 15:01:43.309
Starting Thread 06 at: 2020-11-22 15:01:43.309
Starting Thread 07 at: 2020-11-22 15:01:43.309
Starting Thread 08 at: 2020-11-22 15:01:43.309
Starting Thread 09 at: 2020-11-22 15:01:43.309
Starting Thread 10 at: 2020-11-22 15:01:43.309
10
Stopping Thread 10 at: 2020-11-22 15:01:44.310
9
Stopping Thread 09 at: 2020-11-22 15:01:45.311
8
Stopping Thread 08 at: 2020-11-22 15:01:46.309
7
Stopping Thread 07 at: 2020-11-22 15:01:47.314
6
Stopping Thread 06 at: 2020-11-22 15:01:48.311
5
Stopping Thread 05 at: 2020-11-22 15:01:49.310
4
Stopping Thread 04 at: 2020-11-22 15:01:50.310
3
Stopping Thread 03 at: 2020-11-22 15:01:51.311
2
Stopping Thread 02 at: 2020-11-22 15:01:52.309
1
Stopping Thread 01 at: 2020-11-22 15:01:53.311

推荐阅读