package main
import (
"fmt"
"os"
"os/signal"
"syscall"
)
func main() {
signal_chan := make(chan os.Signal, 1)
signal.Notify(signal_chan,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT)
exit_chan := make(chan int)
go func() {
for {
s := <-signal_chan
switch s {
// kill -SIGHUP XXXX
case syscall.SIGHUP:
fmt.Println("hungup")
// kill -SIGINT XXXX or Ctrl+c
case syscall.SIGINT:
fmt.Println("Warikomi")
// kill -SIGTERM XXXX
case syscall.SIGTERM:
fmt.Println("force stop")
exit_chan <- 0
// kill -SIGQUIT XXXX
case syscall.SIGQUIT:
fmt.Println("stop and core dump")
exit_chan <- 0
default:
fmt.Println("Unknown signal.")
exit_chan <- 1
}
}
}()
code := <-exit_chan
os.Exit(code)
}
golang Golang中信号量的示例实现和使用
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)
}
}