Skip to content

Instantly share code, notes, and snippets.

@josvaal
Created July 25, 2024 16:20
Show Gist options
  • Save josvaal/dd576e46cf8038fca31a249266931ef7 to your computer and use it in GitHub Desktop.
Save josvaal/dd576e46cf8038fca31a249266931ef7 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
//Solución de Dijkstra
// Número de filósofos
const numPhilosophers = 5
const mealsPerPhilosopher = 3 // Número de comidas por filósofo
// Estructura que representa un filósofo
type Philosopher struct {
id int
leftFork, rightFork *sync.Mutex // Los tenedores a la izquierda y derecha del filósofo
}
// Método que simula el comportamiento de un filósofo (pensar y comer)
func (p *Philosopher) dine(wg *sync.WaitGroup) {
defer wg.Done() // Indica que este filósofo ha terminado su trabajo cuando termine
for i := 0; i < mealsPerPhilosopher; i++ { // Cada filósofo comerá el número definido de veces
p.think() // Simula el tiempo que el filósofo pasa pensando
p.eat() // Simula el tiempo que el filósofo pasa comiendo
}
}
// Método que simula el tiempo de pensamiento del filósofo
func (p *Philosopher) think() {
fmt.Printf("Filósofo %d está pensando\n", p.id)
time.Sleep(time.Duration(1+rand.Intn(5)) * time.Second) // Duerme por un tiempo aleatorio entre 1 y 5 segundos
}
// Método que simula el tiempo de comida del filósofo
func (p *Philosopher) eat() {
p.leftFork.Lock() // Tomar el tenedor a la izquierda
p.rightFork.Lock() // Tomar el tenedor a la derecha
fmt.Printf("Filósofo %d está comiendo\n", p.id)
time.Sleep(time.Duration(1+rand.Intn(5)) * time.Second) // Duerme por un tiempo aleatorio entre 1 y 5 segundos
p.rightFork.Unlock() // Soltar el tenedor a la derecha
p.leftFork.Unlock() // Soltar el tenedor a la izquierda
fmt.Printf("Filósofo %d ha terminado de comer\n", p.id)
}
func main() {
var wg sync.WaitGroup // WaitGroup para esperar a que todos los filósofos terminen
forks := make([]*sync.Mutex, numPhilosophers) // Crear un arreglo de tenedores
philosophers := make([]*Philosopher, numPhilosophers) // Crear un arreglo de filósofos
// Inicializar los tenedores
for i := 0; i < numPhilosophers; i++ {
forks[i] = &sync.Mutex{}
}
// Crear los filósofos y asignarles tenedores
for i := 0; i < numPhilosophers; i++ {
philosophers[i] = &Philosopher{
id: i + 1,
leftFork: forks[i], // El tenedor a la izquierda del filósofo
rightFork: forks[(i+1)%numPhilosophers], // El tenedor a la derecha del filósofo
}
}
// Añadir el número de filósofos al WaitGroup
wg.Add(numPhilosophers)
for i := 0; i < numPhilosophers; i++ {
go philosophers[i].dine(&wg) // Iniciar un goroutine para cada filósofo
}
wg.Wait() // Esperar a que todos los filósofos terminen
fmt.Println("Todos los filósofos han terminado de comer")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment