package main
import (
"fmt"
"math/rand"
)
type empty struct{}
type semaphore chan empty
// acquire n resources
func (s semaphore) Acquire(n int) {
e := empty{}
for i := 0; i < n; i++ {
s <- e
}
}
// release n resources
func (s semaphore) Release(n int) {
for i := 0; i < n; i++ {
<-s
}
}
/* mutex */
func (s semaphore) Lock() { s.Acquire(1) }
func (s semaphore) Unlock() { s.Release(1) }
/* signal-wait */
func (s semaphore) Signal() { s.Release(1) }
func (s semaphore) Wait(n int) { s.Acquire(n) }
func generateRandomNumbers(n int) <-chan float64 {
ch := make(chan float64)
sem := make(semaphore, n)
for i := 0; i < n; i++ {
sem.Wait(1)
go func() {
fmt.Println("put -> |=======|")
ch <- rand.Float64()
sem.Signal()
}()
}
// launch extra goroutine to eventually close ch
go func() {
fmt.Println("waiting to close")
sem.Wait(n)
close(ch)
}()
return ch
}
func main() {
for result := range generateRandomNumbers(10) {
fmt.Printf("read <- %f |=======|\n", result)
}
}
golang Golang使用链表实现基本堆栈的示例
package main
import (
"fmt"
"sync"
)
type Node struct {
value int
next *Node
}
type StackOfInts struct {
head *Node
length int
sync.Mutex
}
func (s *StackOfInts) Push(n int) {
s.Lock()
defer s.Unlock()
this := s.head
s.head = &Node{
value: n,
next: this,
}
s.length++
}
func (s *StackOfInts) Pop() int {
s.Lock()
defer s.Unlock()
popped := s.head
s.head = s.head.next
s.length--
return popped.value
}
func (s *StackOfInts) Len() int {
s.Lock()
defer s.Unlock()
return s.length
}
func (s *StackOfInts) IsEmpty() bool {
s.Lock()
defer s.Unlock()
return s.head == nil
}
func NewStack() *StackOfInts {
return &StackOfInts{
head: nil,
}
}
func main() {
s := NewStack()
s.Push(10)
s.Push(20)
s.Push(30)
s.Push(40)
for s.Len() > 0 {
fmt.Println(s.Pop())
}
fmt.Println(s.IsEmpty())
}