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:
- Create a new application with app.New().
- Configure the main window with app.NewWindow().
- Design content using Fyne containers and widgets.
- 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() }
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() }
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) } }
- Event notification from the model:
package models type Observer interface { OnVehiculoEntra(id, cajon, espaciosDisponibles, capacidad int) OnVehiculoSale(id, cajon, espaciosDisponibles, capacidad int) }
- 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) }
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:
- Be arranged in two rows with even spacing.
- Dynamically change color (red for busy, black for available).
Identified Problems
- 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()).
- 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") }
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; iVisual 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() }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!

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

ThebytespackageinGoiscrucialforhandlingbyteslicesandbuffers,offeringtoolsforefficientmemorymanagementanddatamanipulation.1)Itprovidesfunctionalitieslikecreatingbuffers,comparingslices,andsearching/replacingwithinslices.2)Forlargedatasets,usingbytes.N

You should care about the "strings" package in Go because it provides tools for handling text data, splicing from basic strings to advanced regular expression matching. 1) The "strings" package provides efficient string operations, such as Join functions used to splice strings to avoid performance problems. 2) It contains advanced functions, such as the ContainsAny function, to check whether a string contains a specific character set. 3) The Replace function is used to replace substrings in a string, and attention should be paid to the replacement order and case sensitivity. 4) The Split function can split strings according to the separator and is often used for regular expression processing. 5) Performance needs to be considered when using, such as

The"encoding/binary"packageinGoisessentialforhandlingbinarydata,offeringtoolsforreadingandwritingbinarydataefficiently.1)Itsupportsbothlittle-endianandbig-endianbyteorders,crucialforcross-systemcompatibility.2)Thepackageallowsworkingwithcus

Mastering the bytes package in Go can help improve the efficiency and elegance of your code. 1) The bytes package is crucial for parsing binary data, processing network protocols, and memory management. 2) Use bytes.Buffer to gradually build byte slices. 3) The bytes package provides the functions of searching, replacing and segmenting byte slices. 4) The bytes.Reader type is suitable for reading data from byte slices, especially in I/O operations. 5) The bytes package works in collaboration with Go's garbage collector, improving the efficiency of big data processing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools
