Skip to content

Instantly share code, notes, and snippets.

@badaozhai
Last active July 3, 2019 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save badaozhai/5ff7a398c7b1c89d72e76b22546f1eb3 to your computer and use it in GitHub Desktop.
Save badaozhai/5ff7a398c7b1c89d72e76b22546f1eb3 to your computer and use it in GitHub Desktop.
/**
* Created by chenjian on 2016/6/27.
*/
package main
import (
"fmt"
"runtime"
"sync"
"reflect"
"time"
)
type Sushi string
func test1() {
var ch <-chan Sushi = Producer()
for s := range ch {
fmt.Println("Consumed", s)
}
}
func Producer() <-chan Sushi {
ch := make(chan Sushi)
go func() {
ch <- Sushi("海老握り") // Ebi nigiri
ch <- Sushi("鮪とろ握り") // Toro nigiri
close(ch)
}()
return ch
}
func race() {
wati := make(chan struct{})
n := 0
go func() {
n++
close(wati)
}()
n++
<-wati
fmt.Println(n)
}
func test2() {
var cnt int = 0 //全局计数器
mylock := &sync.Mutex{} //互斥锁
arr := [11]int{}
for i := 0; i < 10; i++ {
fmt.Print("Result of ", i, ":")
go func() {
arr[i] = i + i*i
fmt.Println(arr[i])
mylock.Lock() //写之前加锁
cnt++
mylock.Unlock() //写之后解锁
}()
}
for {
mylock.Lock() //读之前加锁
temp := cnt
mylock.Unlock() //读之后加锁
runtime.Gosched() //协程切换
if temp >= 10 {
break
}
}
for i := 0; i < 11; i++ {
fmt.Println("Result of ", i, ":", arr[i])
}
fmt.Println("Done")
}
func test3() {
chs := make([]chan int, 10)
arr := [11]int{}
for i := 0; i < 10; i++ {
chs[i] = make(chan int)
go func(ch chan int, i int) {
arr[i] = i + i*i
ch <- 1
close(ch)
}(chs[i], i)
}
//for _, ch := range chs {
// <-ch // 读channel
//}
for i := 0; i < 11; i++ {
fmt.Println("Result of ", i, ":", arr[i])
}
fmt.Println("Done")
}
func test4() {
ch := make(chan int)
go func() {
ch <- 3
fmt.Println(111)
}()
<-ch
fmt.Println(222)
}
func test_5() {
s := make(chan string) //宣告一個 channel 變數
s <- "hello" //寫入 channel (sender)
val := <-s //讀取 channel (receiver)
fmt.Println(val)
}
func test6() {
s := make(chan string,12)
fmt.Println(s)
fmt.Println(reflect.TypeOf(s))
a := make([]string,10)
fmt.Println(a)
fmt.Println(reflect.TypeOf(a))
go func() {
for i := 0; i < 10; i++ {
fmt.Println("sender hello", i)
s <- fmt.Sprintf("receiver hello %d", i)
}
}()
for i := 0; i < 10; i++ {
val := <-s
fmt.Println(val)
}
}
func main() {
queue := make(chan int, 1)
go Producer1(queue)
go Consumer(queue)
time.Sleep(1e9) //让Producer与Consumer完成
}
func Producer1 (queue chan<- int){
for i:= 0; i < 10; i++ {
queue <- i
}
}
func Consumer( queue <-chan int){
for i :=0; i < 10; i++{
v := <- queue
fmt.Println("receive:", v)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment