【问题标题】:Python Threading Parameters IssuePython线程参数问题
【发布时间】:2018-08-22 04:31:07
【问题描述】:

我已经尝试了大约半个小时,但似乎无法理解我在这里做错了什么。 工作代码:

import threading
from time import sleep


def printX():
    threading.Timer(5.0, printX).start()
    print("five")


printX()
while True:
    print("1")
    sleep(1)

这可行,但是我需要能够动态分配打印语句的内容以及延迟。 所需代码:

import threading
from time import sleep


def printX(time, message):
    threading.Timer(int(time), printX).start()
    print(str(message)


printX(time, message)
while True:
    print("Rest of the program continues")
    sleep(1)

提前感谢您的帮助:)。

【问题讨论】:

  • 使用args 参数:threading.Timer(time, printX, args=(time, message)).start() -

标签: python python-3.x multithreading parameters parallel-processing


【解决方案1】:

threading.Timer 可以使用args 传递参数:

threading.Timer(int(time), printX, (time, message)).start()

阅读更多its doc

【讨论】:

    【解决方案2】:

    另一种方法是使用 printX 作为内部函数来定义一个类。

    class thread:
    
        def __init__(self, time, message):
            self.time = time
            self.message = message
    
        def printX(self):
            threading.Timer(int(self.time), self.printX).start()
            print(str(self.message))
    
    thread(3,"test message").printX()
    
    while True:
        print("Rest of the program continues")
        sleep(1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多