简体   繁体   English

如何使用线程从while循环中获取参数的值?

[英]How to obtain the value of argument from while loop using threading?

I am trying to obtain the changing value of argument (self.num), which is changing in a while loop of a separate thread, every time I need it.我正在尝试获取参数(self.num)的变化值,每次我需要它时,它都会在单独线程的while循环中发生变化。 However, I always get only zero.但是,我总是只得到零。

from time import sleep
from threading import Thread


class Number:
    def __init__(self):
        self.num = 0

    def trend(self):
        while 1:
            self.num += 1

    def trend1(self):
        return self.num

if __name__ == '__main__':
    while 1:
        Thread(target=Number().trend).start()
        print(f"{Number().trend1()=}")
        sleep(0.1)
        print(f"{Number().trend1()=}")

The very first Number defined in Thread can never be referred. Thread 中定义的第一个Number永远不能被引用。 Also, in your while loop, you defined another 2 Number s that are independent to the Thread.此外,在您的 while 循环中,您定义了另外 2 个与线程无关的Number

you just need one Number to do the job:您只需要一个号码即可完成这项工作:

if __name__ == '__main__':
    number = Number()                # save an Number() object as param
    th = Thread(target=number.trend) # create a Thread for its trend()
    th.daemon = True                 # (optional) Thread dies with code
    th.start()                       # start the Thread
    while 1:                          
        print(f"{number.trend1()=}") # call the trend1() in number
        sleep(0.1)
        print(f"{number.trend1()=}")

now, number holds the Number() object for the Thread and counter.现在, number为线程和计数器保存 Number() object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM