python简单示例中的并行多处理 [英] Parallel multiprocessing in python easy example
问题描述
我需要说多处理对我来说是新事物.我读了一些关于它的内容,但是这让我更加困惑.我想通过一个简单的例子来理解它.假设我们在第一个函数中有2个函数,我只是将'a'变量递增,然后将其分配给'number'变量,然后在第二个中,我启动第一个函数,并且每隔一秒钟我要打印一次'number'变量.看起来应该像这样:
I need to say that multiprocessing is something new to me. I read some about it but it makes me more confused. I want to understand it on a simple example. Let's assume that we have 2 functions in first one I just increment 'a' variable and then assign it to 'number' variable, in second I start first function and each every one second I want to print 'number' variable. It should looks like:
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()
我该怎么做?有一种简单而正确的方法吗?
How can I do that? Is there an easy and proper way to do that ?
更新:
我看到了noxdafox的回答,我真的很感谢,但这并不是我想要的.首先,我不想在第一个函数(noxdafox代码中的"main")中发送值.其次,我不想获取所有值,因此无法使用quene.我需要获得每秒的while循环次数.代码应类似于:
I saw noxdafox answer I'm really thankfull but it isn't exactly what I want. First of all I don't want send value in first function ('main' in noxdafox code). Second I don't want to get all values so quene will won't work. I need to get after each second number of while loops. Code should be something like :
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()
如果您运行上述代码,您将得到类似以下内容的代码:
If u run above code you get something like:
但是此蓝色选择值应该相同!那是主要的问题:)
but this blue selected values should be same ! and that's the main problem :)
P.S为您的混乱感到抱歉
P.S sorry for chaos
推荐答案
好,需要一些时间,但我知道了.所有关于在进程之间共享状态现在所有的东西都像魅力一样.代码:
Ok it takes some time but I figured it out. All it was about Sharing state between processes now all it works like charm. Code :
from multiprocessing import Process, Value
import time
def child_process(number):
number.value = 0
while True:
number.value += 1
#print(number)
def main():
num = Value('i')
process = Process(target=child_process, args=(num,))
process.start()
while True:
print("should get same number:", num.value)
time.sleep(1)
if __name__ == "__main__":
main()
这篇关于python简单示例中的并行多处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!