mjcortejo / csc931m-complex-systems

This repository contains the projects done for the CSC931M class
0 stars 0 forks source link

Implement multithreaded for cars agent #19

Closed mjcortejo closed 1 year ago

mjcortejo commented 1 year ago

Use threading library

import threading

Recommended pseudo code:

import simpy
from concurrent.futures import ThreadPoolExecutor

# Function to handle car movement (executed by threads)
def move_car(each_car):
    if not each_car.is_spawned:
        # wait for spawn
        pass
    else:
        message_log = f"""
        Car: {each_car.index}
            origin: {each_car.origin_node}
            dest: {each_car.next_destination_node}
            distance_to_other_cars: {each_car.cars_in_front}
        """ 
        child_canvas.itemconfigure(logs[each_car.index], text=message_log)
        each_car.travel()
    return each_car.arrived

# SimPy car task function
def car_task(env):
    while True:
        # List to store the car movement tasks
        car_movement_tasks = []

        # Create a ThreadPoolExecutor with the desired number of threads
        with ThreadPoolExecutor(max_workers=8) as executor:  # You can adjust max_workers based on the number of cars and available resources
            for index, each_car in enumerate(cars):
                car_movement_tasks.append(executor.submit(move_car, each_car))

        # Wait for all car movement tasks to complete before proceeding to the next iteration
        yield simpy.AllOf(env, car_movement_tasks)

        # Remove completed cars
        cars[:] = [each_car for each_car in cars if not each_car.arrived]

        yield env.timeout(car_task_delay)

# Create the SimPy environment and run the car task
env = simpy.Environment()
env.process(car_task(env))
env.run(until=100)  # Run the simulation for a specific duration
mjcortejo commented 1 year ago

Closed by #26