【发布时间】:2017-11-22 07:09:46
【问题描述】:
我需要说,多处理对我来说是新事物。我读了一些关于它的东西,但这让我更加困惑。我想通过一个简单的例子来理解它。假设我们在第一个函数中有 2 个函数,我只是增加 'a' 变量,然后将其分配给 'number' 变量,第二个我启动第一个函数,并且每隔一秒我想打印 'number' 变量。它应该看起来像:
global number
def what_number():
a=1
while True:
a+=1
number=a
def read_number():
while True:
--> #here I need to start 'what_number' function <--
time.sleep(1)
print(number)
if __name__ == "__main__":
read_number()
我该怎么做?有没有一种简单而正确的方法来做到这一点?
更新:
我看到了 noxdafox 的回答,我真的很感激,但这并不是我想要的。首先,我不想在第一个函数中发送值(noxdafox 代码中的“main”)。其次,我不想获得所有值,因此 quene 将不起作用。我需要在每秒钟的 while 循环数之后得到。代码应该是这样的:
import multiprocessing
import time
number = 0
def child_process():
global number
while True:
number += 1
print(number)
def main():
process = multiprocessing.Process(target=child_process)
process.start()
while True:
print("should get same number:",number)
time.sleep(0.001)
if __name__ == "__main__":
main()
但是这个蓝色选择的值应该是一样的!这是主要问题:)
P.S 对混乱感到抱歉
【问题讨论】:
-
global number? -
@alfasin global 因为我想从其他函数访问它
-
global不是这样使用的
标签: python python-3.x parallel-processing multiprocessing python-multiprocessing