[Python] How to exchange variables between processes in Python in real time_ish. Is the only...

Discussão em 'Python' iniciado por Stack, Fevereiro 24, 2025.

  1. Stack

    Stack Membro Participativo

    from multiprocessing import Process, Manager, Lock, Value
    import time

    class Niao:
    def __init__(self, axle_angle, position_x, position_y, energy, speed):
    self.axle_angle = axle_angle
    self.position_x = position_x
    self.position_y = position_y
    self.energy = energy
    self.speed = speed

    def move(self, new_x, new_y):
    self.position_x.value = new_x
    self.position_y.value = new_y

    class SharedWorld:
    def __init__(self, manager):
    self.lock = Lock()
    self.niao_dict = manager.dict() # Shared dictionary for Niao objects

    def add_niao(self, key, niao):
    with self.lock:
    self.niao_dict[key] = {
    'axle_angle': niao.axle_angle.value, # Store the value directly
    'position_x': niao.position_x.value, # Store the value directly
    'position_y': niao.position_y.value, # Store the value directly
    'energy': niao.energy.value, # Store the value directly
    'speed': niao.speed.value # Store the value directly
    }

    def get_niao(self, key):
    with self.lock:
    niao_data = self.niao_dict[key]
    return Niao(
    Value('d',niao_data['axle_angle']), # Create new Value object
    Value('d', niao_data['position_x']), # Create new Value object
    Value('d', niao_data['position_y']), # Create new Value object
    Value('d', niao_data['energy']), # Create new Value object
    Value('d', niao_data['speed']) # Create new Value object
    )

    def move_niao(self, key, new_x, new_y):
    with self.lock:
    self.niao_dict[key]['position_x'] = new_x # Update the value directly
    self.niao_dict[key]['position_y'] = new_y # Update the value directly

    def niao_worker(shared_world, key):
    while True:
    with shared_world.lock: # Lock access to shared data
    niao_data = shared_world.niao_dict[key]
    print(f"Niao Worker accessing: Niao Position ({niao_data['position_x']},
    {niao_data['position_y']})")
    pos_x = niao_data['position_x']
    pos_y = niao_data['position_y']

    # Move Niao object
    shared_world.move_niao(key, pos_x + 5.0, pos_y + 6.0)

    with shared_world.lock: # Lock access to shared data
    niao_data = shared_world.niao_dict[key]
    print(f"Niao Worker accessing post update: Niao Position ({niao_data['position_x']}, {niao_data['position_y']})")

    time.sleep(1) # Delay for 1 second

    def worker(shared_world, key):
    while True:
    niao = shared_world.get_niao('niao_0')
    print(f"Worker accessing: Position ({niao.position_x.value}, {niao.position_y.value})")
    # Delay to reduce the loop's speed
    time.sleep(1) # Delay for 1 second (adjust as needed)

    if __name__ == "__main__":
    manager = Manager()
    shared_world = SharedWorld(manager)

    # Add Niao objects to the shared world
    shared_world.add_niao('niao_0', Niao(
    Value('d', 0.0), # niao_axle_angle
    Value('d', 0.0), # niao_position_x
    Value('d', 0.0), # niao_position_y
    Value('d', 0.0), # niao_energy
    Value('d', 0.0) # niao_speed
    ))

    # Create and start Niao processes
    niao_processes = []
    for key in ['niao_0']:
    p = Process(target=niao_worker, args=(shared_world, key))
    niao_processes.append(p)
    p.start()

    # Create and start Food processes
    food_processes = []
    for key in ['food_1']:
    p = Process(target=worker, args=(shared_world, key))
    food_processes.append(p)
    p.start()

    # Wait for all processes to finish
    for p in niao_processes + food_processes:
    p.join()


    This code is the culmination of multiple attempts to share variables between processes in Python. I think I have understood that the dictionaries return shadow copies of the data and that is why the data is not being updated. I am attempting to run multiple niao objects in real time at 25 fps but all the objects need to know the position of each other and much more. I have limited programming experience but being able to exchange real data between processes is such an obvious thing to do that I struggle to understand why it is so difficult. I do not want to use queues and pipes. I have looked at using Cython to improve access speed but concluded this only added to the complexity and it should be possible to do this with Python. Can anyone tell me that exchanging parameters this way is possible.

    Continue reading...

Compartilhe esta Página