重写多协程问题
This commit is contained in:
18
main.go
18
main.go
@@ -2,8 +2,9 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"goLearn/model"
|
"goLearn/model"
|
||||||
"goLearn/reflect"
|
"goLearn/test"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
var Ch = make(chan model.Task, 3)
|
var Ch = make(chan model.Task, 3)
|
||||||
@@ -45,7 +46,20 @@ func main() {
|
|||||||
//ctx := context.WithValue(context.Background(), "value", model.Task{Id: "1", Content: "1"})
|
//ctx := context.WithValue(context.Background(), "value", model.Task{Id: "1", Content: "1"})
|
||||||
//goroutine.Runtask(ctx)
|
//goroutine.Runtask(ctx)
|
||||||
|
|
||||||
reflect.FuncReflect(make([]int, 3))
|
//reflect.FuncReflect(make([]int, 3))
|
||||||
|
|
||||||
|
var mx sync.Mutex
|
||||||
|
|
||||||
|
ch := make(chan int, 10)
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
go test.GoProducer(&mx, ch)
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
go test.GoConsumer(&mx, ch)
|
||||||
|
}
|
||||||
|
time.Sleep(10 * time.Second)
|
||||||
|
defer close(ch)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
19
test/Consumer.go
Normal file
19
test/Consumer.go
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GoConsumer(mx *sync.Mutex, ch chan int) {
|
||||||
|
defer mx.Unlock()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case v := <-ch:
|
||||||
|
mx.Lock()
|
||||||
|
fmt.Println("读取到", v)
|
||||||
|
mx.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
25
test/Producer.go
Normal file
25
test/Producer.go
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
package test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math/rand"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GoProducer(mx *sync.Mutex, ch chan int) {
|
||||||
|
rand.Seed(time.Now().UnixNano())
|
||||||
|
|
||||||
|
// 生成 [0,100) 随机整数
|
||||||
|
randomInt := rand.Intn(100)
|
||||||
|
timech := time.Tick(time.Second)
|
||||||
|
defer mx.Unlock()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-timech:
|
||||||
|
ch <- randomInt
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user