Home > Backend Development > Golang > Technical Report: Development of a Concurrent Parking Simulator in Go

Technical Report: Development of a Concurrent Parking Simulator in Go

Susan Sarandon
Release: 2024-12-24 19:40:11
Original
202 people have browsed it

Reporte Técnico: Desarrollo de un Simulador de Estacionamiento Concurrente en Go

Introduction

This project consists of a concurrent parking simulator developed in Go, using the Fyne graphical library for the user interface. Its objective is to model the behavior of a parking lot in real time, managing the entry and exit of vehicles concurrently and visually showing the updated status of the parking spaces.
The project combines the concepts of concurrency, the Observer design pattern and dynamic rendering in a graphical interface. This report details the use of these tools, the challenges encountered (particularly with the Observer and Fyne pattern), and how they were resolved, with the goal of providing a technical reference for other developers.

1. Fyne initialization

Fyne is a modern library for developing graphical interfaces with Go. Basic initialization follows these steps:

  1. Create a new application with app.New().
  2. Configure the main window with app.NewWindow().
  3. Design content using Fyne containers and widgets.
  4. Call ShowAndRun() to run the application.

In the simulator, a main window was created that integrates the parking lot view and connects to the concurrent logic model:

func main() {
    myApp := app.New()
    mainWindow := myApp.NewWindow("Simulador de Parking")

    estacionamiento := models.NewEstacionamiento(20)
    parkingView := views.NewParkingView()

    mainScene := scenes.NewMainScene(estacionamiento, parkingView)
    mainWindow.SetContent(parkingView.Container)

    mainWindow.ShowAndRun()
}

Copy after login
Copy after login
Copy after login

This basic flow facilitates the separation between the business logic and the graphical interface.

2. Using the Observer Pattern

Why use the Observer pattern

The Observer pattern was used to keep the model and view layers in sync. When a vehicle enters or leaves the parking lot, the model notifies the view, which updates the corresponding graphic elements. This pattern is ideal for systems where multiple components must react to the same event.

Problems encountered when using the Observer pattern in Go

Implementing the Observer pattern in Go can be challenging, especially for those accustomed to its implementation in object-oriented languages ​​like Java or C#. A common problem using this pattern in Go is handling concurrency and deadlocks when notifying observers.

Initially, iterating over observers registered in the model (Parking) to report events resulted in race conditions and crashes. This was happening because the method that registered new observers was not properly protected, causing simultaneous accesses to the observer list.

How it was solved
To solve this problem, a mutex (sync.Mutex) was used to protect concurrent access to the observer list. Additionally, secure methods for registering observers and reporting events have been implemented:

func main() {
    myApp := app.New()
    mainWindow := myApp.NewWindow("Simulador de Parking")

    estacionamiento := models.NewEstacionamiento(20)
    parkingView := views.NewParkingView()

    mainScene := scenes.NewMainScene(estacionamiento, parkingView)
    mainWindow.SetContent(parkingView.Container)

    mainWindow.ShowAndRun()
}

Copy after login
Copy after login
Copy after login

Complete implementation in the project
The Parking lot model acts as the observable subject, while the MainScene and other components, such as the graph view, are observers:
1. Observer interface definition:

func (e *Estacionamiento) RegistrarObservador(o Observer) {
    e.mu.Lock()
    defer e.mu.Unlock()
    e.observadores = append(e.observadores, o)
}

func (e *Estacionamiento) NotificarVehiculoEntra(id, cajon, espaciosDisponibles, capacidad int) {
    e.mu.Lock()
    defer e.mu.Unlock()
    for _, o := range e.observadores {
        o.OnVehiculoEntra(id, cajon, espaciosDisponibles, capacidad)
    }
}

func (e *Estacionamiento) NotificarVehiculoSale(id, cajon, espaciosDisponibles, capacidad int) {
    e.mu.Lock()
    defer e.mu.Unlock()
    for _, o := range e.observadores {
        o.OnVehiculoSale(id, cajon, espaciosDisponibles, capacidad)
    }
}
Copy after login
  1. Event notification from the model:
package models

type Observer interface {
    OnVehiculoEntra(id, cajon, espaciosDisponibles, capacidad int)
    OnVehiculoSale(id, cajon, espaciosDisponibles, capacidad int)
}

Copy after login
  1. Observer response:
func (e *Estacionamiento) VehiculoEntra(id int) {
    // Lógica para manejar la entrada del vehículo
    espaciosDisponibles := e.capacidad - e.ocupados
    e.NotificarVehiculoEntra(id, cajon, espaciosDisponibles, e.capacidad)
}

func (e *Estacionamiento) VehiculoSale(id int) {
    // Lógica para manejar la salida del vehículo
    espaciosDisponibles := e.capacidad - e.ocupados
    e.NotificarVehiculoSale(id, cajon, espaciosDisponibles, e.capacidad)
}
Copy after login

This solution ensures that updates are consistent and that race conditions do not affect system performance.

3. Technical Problem: Rendering and Position Calculation

Context

The main technical challenge was calculating the positions of the drawers in the graphical interface and updating their color in real time. The drawers should:

  1. Be arranged in two rows with even spacing.
  2. Dynamically change color (red for busy, black for available).

Identified Problems

  1. Dynamic position calculation: The parking spaces had to be positioned in two rows, with uniform spacing between them. However, calculating and updating these positions was complex as they depended on precise coordinates within a layoutless container (container.NewWithoutLayout()).
  2. Visual Synchronization: When handling multiple concurrent threads, visual inconsistencies arose when trying to update drawer colors in real time. Sometimes changes were not reflected or caused graphical errors.

Position calculation
Absolute coordinates were used to define the initial position and spacing:

func (s *MainScene) OnVehiculoEntra(id, cajon, espaciosDisponibles, capacidad int) {
    s.View.UpdateState(espaciosDisponibles, capacidad, id, cajon, "entra")
}

func (s *MainScene) OnVehiculoSale(id, cajon, espaciosDisponibles, capacidad int) {
    s.View.UpdateState(espaciosDisponibles, capacidad, id, cajon, "sale")
}
Copy after login

Dynamic rendering
Functions were implemented to paint the drawers according to their status:

xStart, yTop, yBottom := float32(185), float32(120), float32(200)
spotSpacing := float32(55)

// Fila superior
for i := 0; i < 10; i++ {
    parkingSpots = append(parkingSpots, fyne.Position{X: xStart + float32(i)*spotSpacing, Y: yTop})
}

// Fila inferior
for i := 0; i < 10; i++ {
    parkingSpots = append(parkingSpots, fyne.Position{X: xStart + float32(i)*spotSpacing, Y: yBottom})
}
Copy after login

Visual Synchronization
To ensure visual changes were consistent with the system state, the main label text and drawer state were updated within a central function:

func main() {
    myApp := app.New()
    mainWindow := myApp.NewWindow("Simulador de Parking")

    estacionamiento := models.NewEstacionamiento(20)
    parkingView := views.NewParkingView()

    mainScene := scenes.NewMainScene(estacionamiento, parkingView)
    mainWindow.SetContent(parkingView.Container)

    mainWindow.ShowAndRun()
}

Copy after login
Copy after login
Copy after login

This ensures an accurate and up-to-date graphical representation at all times.

Conclusion

This project not only achieved its goal of simulating concurrent parking, but also faces practical development problems, such as using the Observer pattern and creating graphical interfaces with Fyne. The problems encountered and the solutions implemented are intended to serve as a guide for other developers starting with Go or facing similar challenges.
The implementation of the Observer pattern in Go, in particular, demonstrates how to handle concurrency safely and efficiently. This report, by documenting these problems and solutions, aims to contribute to the community of programmers interested in learning and applying these tools, facilitating their learning and development process.
If you had any questions about the implementation and solution of this you can consult my github repository: simulador-parking.git

The above is the detailed content of Technical Report: Development of a Concurrent Parking Simulator in Go. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template