Created
February 6, 2018 12:27
-
-
Save husobee/9217b2308d00c394d5699bd76a72b51c to your computer and use it in GitHub Desktop.
example producer-consumer 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 ( | |
"errors" | |
"fmt" | |
"math/rand" | |
"time" | |
) | |
func init() { | |
rand.Seed(time.Now().UnixNano()) | |
} | |
type Queue struct { | |
q [32]string | |
i int | |
} | |
func (q *Queue) Push(s string) error { | |
if q.i == 31 { | |
return errors.New("Full") | |
} | |
q.i++ | |
q.q[q.i] = s | |
return nil | |
} | |
func (q *Queue) Pop() (string, error) { | |
if q.i == 0 { | |
return "", errors.New("Full") | |
} | |
q.i-- | |
return q.q[q.i], nil | |
} | |
func (q *Queue) Len() int { | |
return q.i | |
} | |
func main() { | |
var queue = new(Queue) | |
go consumer(queue) | |
producer(queue) | |
} | |
func consumer(queue *Queue) { | |
for { | |
l := queue.Len() | |
for i := 0; i < l; i++ { | |
s, err := queue.Pop() | |
fmt.Printf("read: %s, %v\n", s, err) | |
if err != nil { | |
time.Sleep(1 * time.Second) | |
break | |
} | |
} | |
} | |
} | |
func producer(queue *Queue) { | |
for { | |
l := queue.Len() | |
for i := l; i < 32; i++ { | |
s := randomString() | |
err := queue.Push(s) | |
fmt.Printf("wrote: %s, %v\n", s, err) | |
if err != nil { | |
time.Sleep(1 * time.Second) | |
break | |
} | |
} | |
} | |
} | |
func randomString() string { | |
w := make([]byte, 5) | |
rand.Read(w) | |
return fmt.Sprintf("%X", w) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment