How to limit the number of Go routines that are allowed to do some work at the "same" time

Hello,

I’m learning Go on Coursera and for my last exercise I have to implement the “dinner philosopher” algorithm.

  • 5 Philosophers can eat. Each one of them eat 3 times
  • only 2 can eat at the same time
  • there is 5 Chopsticks

I want to define a host function which have to control that only 2 philosophers can eat at the same time.
Due to missing knowledge I have difficulties to implement this.
I have tried to use a channel and send a philosopher on the channel, but I still don’t know/understand how can I limit the number of philosopher that are allowed to eat at the same time.

Thanks a lot in advance!

package main

import (
"fmt"
"sync"
"time"
)

type ChopS struct {
    sync.Mutex
}

type Philosopher struct {
    number          int
    leftCs, rightCs *ChopS
}

func (p Philosopher) GetNumber() int {
     return p.number
}

func (p Philosopher) Eat(wg *sync.WaitGroup) {
   for i := 1; i <= 3; i++ {
	p.leftCs.Lock()
	p.rightCs.Lock()
	fmt.Println("starting to eat <", p.number, ">")
	fmt.Println("Finishing eating <", p.number, ">")
	p.leftCs.Unlock()
	p.rightCs.Unlock()
	time.Sleep(2 * time.Second)
   }

}

func NewPhilospher(number int, leftCs, rightCs *ChopS) Philosopher {
   var p Philosopher

   p.number = number
   p.leftCs = leftCs
   p.rightCs = rightCs

  return p
}

func createChops() []*ChopS {
    CSticks := make([]*ChopS, 5)
    for i := 0; i < 5; i++ {
	    CSticks[i] = new(ChopS)
    }
    return CSticks
}

func createPhilosophers() []Philosopher {

    var philos []Philosopher

    CSticks := createChops()
    for i := 0; i < 5; i++ {
	   philos = append(philos, NewPhilospher(i, CSticks[i], CSticks[(i+1)%5]))
    }

    return philos
}

func host() {

   // only 2 Philosophers can eat at the same time
}

func main() {
    philos := createPhilosophers()
    var wg sync.WaitGroup

    for i := 0; i < 5; i++ {
	    wg.Add(1)
	    go philos[i].Eat(&wg)
    }

   wg.Wait()
}

https://play.golang.org/p/EIodyyym-F4

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.