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

Yas*_*oel 1 go goroutine

参考示例,我想在作业初始化和终止之间添加预定义的延迟。我已将数据(即 jobid 和 waittime)存储在地图中。然后我将整个映射复制到与映射相同结构类型的通道中。但我无法在 go 例程调用中获取地图值。请帮助我,我是 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
}
}
Run Code Online (Sandbox Code Playgroud)

abh*_*ink 5

您的代码有一些问题。

首先,您无法直接从通道访问结构成员。也就是说,这一行是错误的:

a, b := <-jobs.id, <-jobs.waitime
Run Code Online (Sandbox Code Playgroud)

jobs是一个通道。它没有任何名为id或 的成员waittimeVertex这些是它应该传输的结构的成员。将此行更改为:

job := <-jobs
a, b := job.id, job.waitime
Run Code Online (Sandbox Code Playgroud)

但现在,您的代码声明b但不使用它。要修复此问题,请取消对以下调用的注释time.Sleep

time.Sleep(time.Sleep(time.Duration(b))) !INCORRECT CALL
Run Code Online (Sandbox Code Playgroud)

但这种说法是完全错误的。time.Sleep需要一个类型的参数time.Duration并且不返回任何内容。要修复,请进行以下更改:

time.Sleep(time.Duration(b) * time.Millisecond)
Run Code Online (Sandbox Code Playgroud)

这应该能让你的代码运行。