简体   繁体   English

python-线程和无限循环

[英]python - threading and infinite loops

inside the main python script, at a point variable VAR is set and thread THR is executed with variable VAR as starting value. 主Python脚本的内部,在一个点变量VAR设定和线程THR与可变执行VAR作为起始值。
within THR there's an infinite loop, which prints VAR every 500 ms . THR有一个无限循环,每500 毫秒打印一次VAR
meanwhile the main script crunches some more data and VAR is updated. 同时,主脚本处理了更多数据,并更新了VAR

how do I reflect the change to THR , so that the printed output will change as well, without killing it and spawning a new one? 我如何将更改反映到THR ,以便打印输出也将发生变化,而不会杀死它并产生新的输出?

this is a very rough simplification of the code I have of course, but I'd rather read and focus on an example skeleton rather than on my particular case. 当然,这是我的代码的非常粗略的简化,但是我宁愿阅读并专注于示例框架而不是我的特殊情况。

EDIT: as per request here's the code I have in mind 编辑:根据要求,这里是我所记的代码

import threading

VAR = 0

def function():
    while True:
        global VAR
        while VAR == VAR:
            print VAR
            time.sleep(0.5)

THR = threading.Thread(target=function)
THR.start()
time.sleep(1)
function().VAR = 4 # this doesn't affect the output, only adds a seemingly random whitespace before it
time.sleep(2)
THR.VAR = 5 # nothing changes

You should use a list with your variable inside. 您应该在变量内使用列表。

If you pass the list to the function, you will be able to modify the value of the first position of the list (outside the function) and at the same time you'll see how the thread prints the correct value. 如果将列表传递给函数,则可以修改列表第一个位置的值(函数之外),同时您将看到线程如何打印正确的值。

Pseudocode: 伪代码:

(THREAD)
    while True:
        print list[0]

(MAIN)
    start_thread(list)
    #modify value
    list[0] = X

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

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