I
I
ilitaexperta2019-04-29 01:47:18
go
ilitaexperta, 2019-04-29 01:47:18

What is the order in which requests are processed in Go?

There is a simple server with longpolling on Go. There are 2 endpoints:

http.HandleFunc("/api/pss", pss)
http.HandleFunc("/api/wanna", wanna)
http.ListenAndServe(":8080", nil)

func pss(w http.ResponseWriter, r *http.Request) {
  // Тут пишем в таблицу users и сразу отвечаем клиенту
}

func wanna(w http.ResponseWriter, r *http.Request) {
  done := make(chan struct{})

  go checkDb(done)

  select {
  case <- done:
    doWanna(w)
  case <- time.After(20 * time.Second):
    doWanna(w)
  }
}

func checkDb(done chan<- struct{}) {
  for i := 0; i < 20; i++ {
    // Проверяем изменения в таблице users
    if hasChanges {
      break
    }

    time.Sleep(time.Second)
  }

  done <- struct{}{}
}

func doWanna(w http.ResponseWriter) {
  // Отвечаем клиенту
}

I don't really understand how multithreading/synchronization works in go and I have 2 cases:
1. The client makes a request to api/wanna and then to api/pss
2. The client makes a request to api/pss and then to api/wanna .
In what order will the answer come? Or is it not deterministic in this case? A detailed answer is desirable, and if there is a reference where you can enlighten on this topic.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Shitskov, 2019-04-29
@Zarom

It is not entirely clear what kind of synchronization and multithreading we are talking about. Neither one nor the other is observed in the above code.
If the client executes requests synchronously, it will receive responses in the requested sequence. If asynchronously, then depending on which request your server has time to process first.

A
Alexander Kubintsev, 2019-05-06
@akubintsev

The questions are a little strange. It looks like you are not interested in what you asked.
On the topic of mutex gorutin synchronization to help https://gobyexample.com/mutexes
But in general, it makes sense to run checkDb as a separate eternal gorutin at the highest level and write from it to the lastChange global variable, which the http handler will pick up without blocking.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question