【发布时间】:2020-04-18 19:48:47
【问题描述】:
因为我不能简单地运行带有 pool.apply_async 和全局变量的程序,所以我需要帮助。我无法解决共享内存的问题。 简短描述一个程序流程:
这个程序应该如何工作: 变量 config.variable 是一个标志 - 默认为 False。如果此标志的线程值出现问题,则应将其设置为 Thru 并且值 True 应停止/暂停。 换一种说法 想法是异步进程中的失败应该停止/暂停程序。
我厌倦了用多处理值和管理器做一些事情,但没有结果。我不知道这是我的失败,或者它永远不会起作用。我太弱了,无法解决这个问题。技能不够。自学很难。 我读过类似的线程,例如Python share values 或Python multiprocessing Pool.apply_async with shared variables (Value),但是关于将参数传递到线程中。大多数其他示例使用 Value 或 Manager,但使用 Process 并且此解决方案对我有用。
问题是: 我可以为 pool.apply_async 使用 Value 或 Manager 吗?如何更改全局变量。 我应该为布尔 True 和 False 使用什么样的类型代码
我读到这个:Sharing state between processes
请帮我看看我应该怎么写。 我附上简单的代码。 有人可以编辑它并添加缺失的行吗? 我无法将 apply_async 更改为 process。
文件 config.py
variable1 = False
文件 main.py
import config
from multiprocessing import Pool
import time
import sys
def func2():
try:
config.variable1 = True
print('Global Variable in thread {}'.format(config.variable1))
except Exception as e:
print(e)
if __name__ == '__main__':
while 1:
time.sleep(1)
try:
pool = Pool(4)
pool.apply_async(func2)
pool.close()
pool.join()
except Exception as e:
print(e)
# print(config.variable1)
print('Global Variable in main loop {}'.format(config.variable1))
if config.variable1 is True:
sys.exit(0)
在这种情况下如何使用 Value 或 Manager? 有人可以添加几行吗?
感谢您的帮助和解释。
【问题讨论】:
-
大多数其他示例使用 Value 或 Manager,但使用 Process 并且此解决方案对我有用。 我很困惑,什么有效或无效?另外,我看不到
except Exception as e:的意义,我相信它是气馁的。我建议为该池使用上下文管理器,并编写while True:而不是while 1:。事实上,这个循环的目的是什么? -
不要使用 pool.apply_asynch 更改全局变量。而 1 仅用于测试原因。我写这个是因为我等待更改值 config.variable1。我尝试将 Menager 用作 menager:但我卡住了。我的变量的值没有改变
-
Martineau - 您的回答仅对“我建议为该池使用上下文管理器”有所帮助”不在主题上。谢谢帮助
-
好吧,这更有意义了。
标签: python asynchronous global-variables apply threadpool