This is a creation in Article, where the information may have evolved or changed.
Directly on the code
1, no time-outs
PackageMainImport("FMT" "Time")funcMain () {//Storage of production channelJobchan: = Make(Chan int, -)//Notify if all tasks are completedEndchan: = Make(Chan BOOL)GoProduction (Jobchan)GoWorker (Jobchan, Endchan)Select{ Case<-endchan:fmt. Println ("The consumption is done ......... .....")return Case<-time. After (time. Second * -): FMT. Println ("Time-out ...... ..........")return}}//ConsumptionfuncWorker (Jobchan <-Chan int, EndchanChan BOOL) { forJob: =RangeJobchan {fmt. Println ("Consumption:", Job)}//end of consumption, notify EndchanEndchan <-true}//ProductionfuncProduction (JobchanChan<-int) { forI: =1; I <=Ten; i++ {fmt. Println ("Production:", i) Jobchan <-i}//Close channel to prevent consumer congestion Close(Jobchan)}
Execution Result:
Visible production and consumption asynchronous concurrent execution.
2, when timeout (timeout setting dot, and increase consumption processing time)
PackageMainImport("FMT" "Time")funcMain () {//Storage of production channelJobchan: = Make(Chan int, -)//Notify if all tasks are completedEndchan: = Make(Chan BOOL)GoProduction (Jobchan)GoWorker (Jobchan, Endchan)Select{ Case<-endchan:fmt. Println ("The consumption is done ......... .....")return Case<-time. After (time. Second *5): FMT. Println ("Time-out ...... ..........")return}}//ConsumptionfuncWorker (Jobchan <-Chan int, EndchanChan BOOL) { forJob: =RangeJobchan {fmt. Println ("Consumption:", job)//Increase consumption processing timeTime. Sleep(1* Time. Second)}//end of consumption, notify EndchanEndchan <-true}//ProductionfuncProduction (JobchanChan<-int) { forI: =1; I <=Ten; i++ {fmt. Println ("Production:", i) Jobchan <-i}//Close channel to prevent consumer congestion Close(Jobchan)}
Execution results
Timeout after 5 seconds (there is still data in the queue that has not been processed).