都是golang的小例子 因为不能高亮的原因就选择了code=c
output:
read from chan c1
select over
package main
import(
"fmt"
"time"
"strconv"
)
var c chan int
func ready(w string, sec int) {
time.Sleep(int64(sec) * 1e9)
fmt.Println(w,"is ready!")
c <- 1
}
func main() {
c = make(chan int)
for k := 0; k < 10; k ++ {
go ready(strconv.Itoa(k) + " thread",k)
}
fmt.Println("I'm watiting, but not too long")
var i int
L: for {
select {
case <-c:
i ++
if i > 9 {
break L
}
}
}
}
package main
import (
"fmt"
)
func main() {
ch := make(chan int)
quit := make(chan bool)
go shower(ch, quit)
for i := 0; i < 10; i++ {
ch <- i
}
quit <- false
}
func shower(c chan int, quit chan bool) {
for {
select {
case j := <-c:
fmt.Printf("%d\n", j)
case <- quit:
break
}
}
}
func toString(any interface {} ) string {
switch any.(type) {
case string:
return any.(string)
case int:
return strconv.Itoa(any.(int))
case bool:
return strconv.Btoa(any.(bool))
default:
panic("the type "+reflect.TypeOf(any).String()+" is not support ")
}
return ""
}
func main() {
cmd := exec.Command("ps","-e","-opid,ppid,comm")
output ,_ := cmd.Output()
child := make(map[int]*vector.IntVector)
for i, line := range strings.Split(string(output), "\n") {
if i == 0 || len(line) == 0 {
continue
}
field := strings.Fields(line)
p, _ := strconv.Atoi(field[0])
pp, _ := strconv.Atoi(field[1])
if child[pp] == nil {
child[pp] = new (vector.IntVector)
}
child[pp].Push(p)
}
sortpp := make([]int,len(child))
i := 0
for k, _ := range child {
sortpp[i] = k
i ++
}
sort.Ints(sortpp)
for _, pp := range sortpp {
length := child[pp].Len()
fmt.Printf("Pid %d has %d child", pp, length)
if length == 1 {
fmt.Printf(": %v\n", []int(*child[pp]))
} else {
fmt.Printf("ren: %v\n", []int(*child[pp]))
}
}
}
package main
import(
"time"
)
func main() {
var c1 = make(chan int)
var c2 = make(chan int)
go func() {
time.Sleep(3e9)
c1 <- 1
// c2 <- 2
}()
select {
case <-c1:
println("read from chan c1")
case <-c2:
println("read from chan c2")
// default:
// println("defalut")
}
println("select over")
}
output:
read from chan c1
select over