Python线程参数问题

时间:2018-08-22 04:31:07

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

我已经尝试了大约半小时,但似乎无法将我的错误全神贯注。 工作代码:

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)

非常感谢您提前提供帮助:)。

2 个答案:

答案 0 :(得分:1)

greenlock-express可以使用threading.Timer传递参数:

args

进一步了解its doc

答案 1 :(得分:1)

另一种方法是定义一个将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)
相关问题