This is a creation in Article, where the information may have evolved or changed.
In many Golang entry articles, the use of concurrent examples are generally written;
Package Mainimport ( "FMT", "Time") func main () { messages: = Make (chan int) go func () { time . Sleep (time. Second * 3) messages <-1 } () go func () {Time . Sleep (time. Second * 2) messages <-2 } () go func () {time. Sleep (time. Second * 1) messages <-3 } () go func () {for I: = range Messages {FMT. Println (i)}} () time. Sleep (time. Second * 5)}
My previous project, too, has been written like this. Today and the discussion in the group, only to realize that this writing is actually more ugly.
Can actually be achieved through this.
Package Mainimport ( "FMT" "io/ioutil" " Log" "net/http" "Sync") func main () { urls: = [] String{ "Http://www.reddit.com/r/aww.json", "Http://www.reddit.com/r/funny.json", "Http://www.reddit.com/r/programming.json",} jsonresponses: = Make (chan string) var wg sync. Waitgroup WG. ADD (len) for _, URL: = range URLs {go func (URL string) {defer WG. Done () res, err: = http. Get (URL) if err ! = Nil {log. Fatal (Err)} else {defer res. Body.close () body, err: = ioutil. ReadAll (Res. Body) If err ! = Nil {log. Fatal (Err)} else {jsonresponses <-string(Body)}}} (URL)} go func () {for response: = range Jsonres ponses {fmt. PRINTLN (Response)}} () WG. Wait ()}
This is simpler and more convenient to use. In terms of performance, it should be better than Chan.
One of my previous cases was that the client sent an HTTP request, the server received the request, and then opened N Go routine, and then after each processing was completed, passed to the main thread through Chan, the main thread judged whether Chan received all the requests, And then respond again.
Is the first method to use.
Today it is reconstructed under the suggestion of the body of the group. Use list to process each user request.
For example, there is a global map variable: map[int]list, each request to create a towering unique random number or SessionID, and then each go rouine after processing, according to SessionID to find the corresponding list, insert data.
You can use the list to implement the mechanism of the asynchronous queue to avoid locks.
So specifically in this record down, of course, the reference of the newcomers.