Golang Goroutine synchronization with channel

Viewed 452

I have the following program where the HTTP server is created using gorilla mux. When any request comes, it starts goroutine 1. In processing, I am starting another goroutine 2. I want to wait for goroutine 2's response in goroutine 1? How I can do that? How to ensure that only goroutine 2 will give the response to goroutine 1?

There can be GR4 created by GR3 and GR 3 should wait for GR4 only.

GR = Goroutine

enter image description here

SERVER

    package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "strconv"
    "time"

    "github.com/gorilla/mux"
)

type Post struct {
    ID    string `json:"id"`
    Title string `json:"title"`
    Body  string `json:"body"`
}

var posts []Post

var i = 0

func getPosts(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    i++
    fmt.Println(i)
    ch := make(chan int)
    go getTitle(ch, i)

    p := Post{
        ID: "123",
    }
    // Wait for getTitle result and update variable P with title

    s := <-ch
    //

    p.Title = strconv.Itoa(s) + strconv.Itoa(i)
    json.NewEncoder(w).Encode(p)
}

func main() {

    router := mux.NewRouter()
    posts = append(posts, Post{ID: "1", Title: "My first post", Body: "This is the content of my first post"})
    router.HandleFunc("/posts", getPosts).Methods("GET")
    http.ListenAndServe(":9999", router)
}

func getTitle(resultCh chan int, m int) {
    time.Sleep(2 * time.Second)
    resultCh <- m
}

CLIENT

package main

import (
  "fmt"
  "net/http"
  "io/ioutil"
    "time"
)


func main(){

for i :=0;i <100 ;i++ {

go main2()

}

    time.Sleep(200 * time.Second)

}

func main2() {

  url := "http://localhost:9999/posts"
  method := "GET"

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, nil)

  if err != nil {
    fmt.Println(err)
  }
  res, err := client.Do(req)
  defer res.Body.Close()
  body, err := ioutil.ReadAll(res.Body)

  fmt.Println(string(body))
}

RESULT ACTUAL

{"id":"123","title":"25115","body":""}

{"id":"123","title":"23115","body":""}

{"id":"123","title":"31115","body":""}

{"id":"123","title":"44115","body":""}

{"id":"123","title":"105115","body":""}

{"id":"123","title":"109115","body":""}

{"id":"123","title":"103115","body":""}

{"id":"123","title":"115115","body":""}

{"id":"123","title":"115115","body":""}

{"id":"123","title":"115115","body":""}

RESULT EXPECTED

 {"id":"123","title":"112112","body":""}
 {"id":"123","title":"113113","body":""}
 {"id":"123","title":"115115","body":""}
 {"id":"123","title":"116116","body":""}
 {"id":"123","title":"117117","body":""}
2 Answers

there are few ways to do this , a simple way is to use channels

change the getTitle func to this

func getTitle(resultCh chan string)  {
   time.Sleep(2 * time.Second)
   resultCh <- "Game Of Thrones"
}

and the getPosts will use it like this

func getPosts(w http.ResponseWriter, r *http.Request) {
   w.Header().Set("Content-Type", "application/json")

   ch := make(chan string)
   go getTitle(ch)


   s := <-ch // this will wait until getTile inserts data to channel 
   p := Post{
       ID: s,
   }

   json.NewEncoder(w).Encode(p)
}

i suspect you are new to go, this is a basic channel usage , check more details here Channels

So the problem you're having is that you haven't really leaned how to deal with concurrent code (not a dis, I was there once). Most of this centers not around channels. The channels are working correctly as @kojan's answer explains. Where things go awry is with the i variable. Firstly you have to understand that i is not being mutated atomically so if your client requests arrive in parallel you can mess up the number:

C1 :          C2:
i == 6        i == 6
i++           i++
i == 7        i == 7

Two increments in software become one increment in actuality because i++ is really 3 operations: load, increment, store.

The second problem you have is that i is not a pointer, so when you pass i to your go routine you're making a copy. the i in the go routine is sent back on the channel and becomes the first number in your concatenated string which you can watch increment. However the i left behind which is used in the tail of the string has continued to be incremented by successive client invocations.

Related