Reputation: 550
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
}
}
Upvotes: 1
Views: 1040
Reputation: 9136
Couple of things are wrong with your code.
First, you can't access struct members directly off the channel. That is, this line is wrong:
a, b := <-jobs.id, <-jobs.waitime
jobs
is a channel. It does not have any members called id
or waittime
. These are the members of the struct Vertex
it's supposed to transfer. Change this line to:
job := <-jobs
a, b := job.id, job.waitime
But now, your code declares b
but does not use it. To fix, uncomment the call to time.Sleep
:
time.Sleep(time.Sleep(time.Duration(b))) !INCORRECT CALL
But this call is completely wrong. time.Sleep
expects an argument of type time.Duration
and returns nothing. To fix, make the following changes:
time.Sleep(time.Duration(b) * time.Millisecond)
This should get your code running.
Upvotes: 5
Reputation: 671
Change:
a, b := <-jobs.id, <-jobs.waitime
to:
job := <-jobs
a, b := job.id, job.waitime
jobs
is a channel not a Vertex.
Upvotes: 1