python并行跑两个case_python简单示例中的并行多处理

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 ?

UPDATE:

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 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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值