【问题标题】:Threading with many function arguments in python在python中使用许多函数参数进行线程化
【发布时间】:2021-03-05 06:59:29
【问题描述】:

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

def functionA(x):
    print(x)

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

但它不起作用。帮帮我。

【问题讨论】:

  • 你的意思是但它不起作用? ...您的代码运行良好。
  • @MauriceMeyer 是的。但它同步运行(依次),而不是同时运行
  • 它正在工作^^。我在写 run() 和 strart() 的时候弄糊涂了。谢谢

标签: python python-3.x function arguments python-multithreading


【解决方案1】:

正如 cmets 中所述,您的代码工作正常,向 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

【讨论】:

  • 它正在工作^^。我在写 run() 和 strart() 的时候很困惑。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
  • 2013-07-24
  • 1970-01-01
  • 2014-08-10
  • 1970-01-01
  • 2021-11-19
相关资源
最近更新 更多