druybew06513 2017-06-07 09:00
浏览 15

无法从Go lang的结构类型通道中获取值

With reference to this example, i want to add a pre-defined delay between job initialization and termination. I have stored the data i.e. jobid and waittime in map. Then i have copied the entire map in a channel of same struct type as map. But i am not able to fetch the map values in go routine calls. Please help me, I am new to Go.

package main

import "fmt"

type Vertex struct {
id, waitime int
}

var m = map[int]Vertex{
1:  {1, 1000},
2:  {2, 2000},
3:  {3, 1000},
4:  {4, 2000},
5:  {5, 1000},
6:  {6, 2000},
7:  {7, 1000},
8:  {8, 2000},
9:  {9, 1000},
10: {10, 2000},
}

func worker(w int, jobs <-chan Vertex, results chan<- int) {
for j := 1; j <= len(m); j++ {
    a, b := <-jobs.id, <-jobs.waitime
    fmt.Println("worker", w, "started job", a)
    //time.Sleep(time.Sleep(time.Duration(b)))
    fmt.Println("worker", w, "finished job", a)
    results <- j * 2
  }
}

func main() {
//n := 5
jobs := make(chan Vertex, 100)
results := make(chan int, 100)

for w := 1; w <= 5; w++ {
    go worker(w, jobs, results)
}
fmt.Println(len(m))
for j := 1; j <= len(m); j++ {
    jobs <- m[j]
}
//close(jobs)

for a := 1; a <= len(m); a++ {
    <-results
}
}
  • 写回答

2条回答 默认 最新

  • dragonsun00000 2017-06-07 09:17
    关注

    Change:

    a, b := <-jobs.id, <-jobs.waitime
    

    to:

    job := <-jobs
    a, b := job.id, job.waitime
    

    jobs is a channel not a Vertex.

    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大