Created
January 25, 2013 14:27
-
-
Save jurka/4634823 to your computer and use it in GitHub Desktop.
Sleeping barber problem solution without Mutex and lock
(http://en.wikipedia.org/wiki/Sleeping_barber_problem)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"time" | |
) | |
const ( | |
BARBERS_AMOUNT = 1 | |
HALL_SITS_AMOUNT = 3 | |
) | |
type Barber struct { | |
val int | |
} | |
type Client struct { | |
val int | |
} | |
func clientProducer(clients chan *Client) { | |
for { | |
time.Sleep(1 * time.Second) | |
clients <- &Client{} | |
} | |
} | |
func cutHear(barber *Barber, client *Client, finished chan *Barber) { | |
// Cutting hear | |
finished <- barber | |
} | |
func BarberShop(clients <-chan *Client) { | |
freeBarbers := []*Barber{} | |
waitingClient := []*Client{} | |
syncBarberChan := make(chan *Barber) | |
//creating barbers | |
for i := 0; i < BARBERS_AMOUNT; i++ { | |
freeBarbers = append(freeBarbers, &Barber{}) | |
} | |
for { | |
select { | |
case client := <-clients: | |
if len(freeBarbers) == 0 { | |
if len(waitingClient) < HALL_SITS_AMOUNT { | |
// client is waiting in the hall | |
waitingClient = append(waitingClient, client) | |
} else { | |
// hall is full - bye-bye client | |
} | |
} else { | |
barber := freeBarbers[0] | |
freeBarbers = freeBarbers[1:] | |
go cutHear(barber, client, syncBarberChan) | |
} | |
// barber finish work | |
case barber := <-syncBarberChan: | |
if len(waitingClient) > 0 { | |
// get client from hall | |
client := waitingClient[0] | |
waitingClient = waitingClient[1:] | |
go cutHear(barber, client, syncBarberChan) | |
} else { | |
// barber is going to sleep | |
freeBarbers = append(freeBarbers, barber) | |
} | |
} | |
} | |
} | |
func main() { | |
clients := make(chan *Client) | |
go clientProducer(clients) | |
go BarberShop(clients) | |
time.Sleep(10 * time.Minute) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment