Python: Update Local Variable in a Parallel Process from Parent Program

后端 未结 3 2142
攒了一身酷
攒了一身酷 2021-01-26 07:14

I am relatively new to programming, and what I am asking might be a task that is not possible. What I want to do is start a parallel process, which will continuously run until

3条回答
  •  臣服心动
    2021-01-26 07:58

    Nothing wrong with a queue here, but it's probably more idiomatic to use "shared memory" instead. Less overhead. Here's an example self-contained program:

    import time
    
    def loop(i):
        while 1:
            print i.value
            i.value += 1
            time.sleep(1)
    
    if __name__ == "__main__":
        from multiprocessing import Process, Value
    
        i = Value("i", 1)  # "i" for integer, initial value 1
        p = Process(target=loop, args=(i,))
        p.start()
        for base in range(100, 600, 100):
            time.sleep(2)
            i.value = base
    

    That will probably ;-) display:

    1
    2
    100
    101
    200
    201
    300
    301
    400
    401
    500
    501
    502
    503
    504
    505
    506
    ...
    

    But caution: in return for being speedier, this is also more brittle. The kinds of data you can share this way are basically inherited from the C language, and aren't generally as rich as Python data types. In the example above, the type code "i" means we're sharing a signed C int, which is usually a 32-bit signed integer. If, for example, i.value reaches 2147483647, and we add 1 to it, it will suddenly become -2147483648 (yup, negative!). Python ints are unbounded, but C ints aren't.

提交回复
热议问题