Golang Goroutine与频道同步

最大值:

我有以下程序,其中使用大猩猩mux创建HTTP服务器。当有任何请求到达时,它将启动goroutine1。在处理中,我正在启动另一个goroutine2。我想等待goroutine 1对goroutine 2的响应吗?我该怎么做?如何确保只有goroutine 2会响应goroutine 1?

可能存在由GR3创建的GR4,并且GR 3应该仅等待GR4。

GR =例行程序

在此处输入图片说明

服务器

    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
}

客户

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))
}

结果实际

{"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":""}

预期结果

 {"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":""}
kojan abzah:

这样做的方法很少,一种简单的方法是使用渠道

将getTitle函数更改为此

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

并且getPosts将像这样使用它

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)
}

我怀疑你是新来走,这是一个基本信道的使用,请参考以下详细信息渠道

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章