Golang http multithreading for every 30 requests

Hi guys! I have this golang code:

    go http.HandleFunc("/", HomePage)
    go http.HandleFunc("/king", KingPage)

for now, i am creating threads only for every handler.
But, i want to create thread for every 30 users,
for example:

    if requests > 30 {
    go http.HandleFunc("/", HomePage)
    } else if requests > 60 {
    go http.HandleFunc("/", HomePage)

but, i want to create one thread for 30 users, right now, it creates 30 threads for 30 users.

Goroutines are no threads. Starting 30 goroutines absolutely does not mean starting 30 threads. You could schedule hundreds of thousands of goroutines; You cannot do that with threads.


Oh, so I did not understand how the gorutines work.
Can you explain to me how it works? (I read the documentation, but I still do not understand it). So goroutine automatically creates all the threads it needs? So I do not have to add any code and this is enough:

go http.HandleFunc("/", HomePage)
go http.HandleFunc("/king", KingPage)

and i dont need to care about anything ? :smiley:

Goroutines are lightweight “threads” that are handled by the Go runtime and aren’t directly translated to OS threads.

Apart from that, the standard library http package already serves each request on a different goroutine for you, you don’t need to do it. So something like this is enough:

http.HandleFunc("/", Handler1)
http.HandleFunc("/other", Handler2)

err := http.ListenAndServe(":8080", nil)

Oh thank you very much. I am really an idiot :smiley:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.