代码如下:
package main
import (
"container/list"
"fmt"
"time"
)
var Ch = make(chan int)
var DataList = list.New()
func ReadChan() {
for {
data := <-Ch
fmt.Println(data)
}
}
func WriteChan() {
for {
if size := DataList.Len(); size > 0 {
data := DataList.Front()
if data.Value != nil {
Ch <- data.Value.(int)
DataList.Remove(data)
}
} else {
time.Sleep(100 * time.Millisecond)
}
}
}
func feed() {
for {
for i := 0; i < 20; i++ {
DataList.PushBack(i)
}
time.Sleep(150 * time.Millisecond)
}
}
func main() {
go WriteChan()
for i := 0; i < 5; i++ {
go ReadChan()
}
feed()
}
本意是写入的数据放入list中缓存,然后协程写入chan, 其他协程读出,对list的读写操作因为是不同的协程所以不用上锁,程序运行一段时间会崩溃,郁闷。。。
更多评论
```
package main
import (
"container/list"
"fmt"
"sync"
"time"
)
var Ch = make(chan int)
var DataList = list.New()
var mutex sync.Mutex
func ReadChan() {
for {
data := <-Ch
fmt.Println(data)
}
}
func WriteChan() {
for {
mutex.Lock()
if size := DataList.Len(); size > 0 {
data := DataList.Front()
if data.Value != nil {
Ch <- data.Value.(int)
DataList.Remove(data)
}
mutex.Unlock()
} else {
mutex.Unlock()
time.Sleep(100 * time.Millisecond)
}
}
}
func feed() {
for {
for i := 0; i < 20; i++ {
mutex.Lock()
DataList.PushBack(i)
mutex.Unlock()
}
time.Sleep(150 * time.Millisecond)
}
}
func main() {
go WriteChan()
for i := 0; i < 5; i++ {
go ReadChan()
}
feed()
}
```
#2