Can you please help to correct below program where timeout not seems working

Work 1 - have 1 second
Work 2 - have 3 second
Total Timeout - 2 sec

program wait for entire 3 seconds and return both values rather than value 
from Work 1

Program >

package main

import (
"fmt"
"time"
"sync"
)


type TestStruct struct {
Name string
}

func main() {

wg := &sync.WaitGroup{}
messges := make(chan *TestStruct, 1)

wg.Add(1)
go Work1(messges, wg, "1")
wg.Add(1)
go Work2(messges, wg, "2")

monitorWorker(wg, messges)

messgesResponse := make(chan []*TestStruct)
go GetWorkerValues(messges, messgesResponse)

headers := make([]*TestStruct, 0)
headers = <-messgesResponse

fmt.Printf("len > %s\n", len(headers))

for i:=0;i<len(headers);i++ {
fmt.Printf("Name > %s\n", headers[i].Name)
}
}



func monitorWorker(wg *sync.WaitGroup, cs chan *TestStruct) {
go func() {
defer close(cs)
wg.Wait()
}()

select {
case <-time.After(2 * time.Second):
return
}
}
func Work1(message chan *TestStruct, wg *sync.WaitGroup, tokenNumber 
string)  {
defer wg.Done()

v1 := new(TestStruct)
v1.Name = tokenNumber
time.Sleep(1 * time.Second)

message <- v1
fmt.Printf("finished %s\n", tokenNumber)
}

func Work2(message chan *TestStruct, wg *sync.WaitGroup, tokenNumber 
string)  {
defer wg.Done()

v1 := new(TestStruct)
v1.Name = tokenNumber
time.Sleep(1 * time.Second)

message <- v1

fmt.Printf("finished %s\n", tokenNumber)
}


func GetWorkerValues(cs <-chan *TestStruct, response chan<- []*TestStruct) {
var val []*TestStruct
for header := range cs {
val = append(val, header)
}
response <- val
}


Thanks,

Abhi

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to