Is golang good to use in multithreaded application?


I am building application which will create a lot of threads. Each thread will connect to different remote server, and each thread has to always communicate with it’s server.

Before I used PHP, it is bad solution for such goal.
My opinion how native threads work:
For example we have 100 threads on single core. And the core will split it’s working time between all threads.

And here from what I have read and understand:

If I open lot goroutines, one goroutine can block the execution of others goroutines. The execution will be passed to other in specific cases (maybe when current goroutine sleeps or something like that). But it doesn’t work like native threads.

I need to make all threads to be executed fluently. Like the same processor’s time for each goroutine. I don’t need that some goroutine is being executed for long time and other will wait..

Can I achieve it with golang ? Or better use another language (which one) ?


Concurrency is one of Go’s main strengths. This doesn’t mean the Go runtime magically solves all issues and cases and makes all your code lightning fast. You can write bad code in any language. But concurrency is built into the language. It hands you several language tools, means to write efficient concurrent code easily, such as goroutines, channels, select statement, synchronization primitives.

A goroutine is a lightweight thread. It costs a lot less than a real OS thread, and multiple goroutines may be multiplexed onto a single OS thread. The spec defines them as “an independent concurrent thread of control within the same address space”.

The go runtime is capable of handling thousands or even hundreds of thousands of goroutines without a problem. As an example, the HTTP server in the standard lib handles all incoming requests by launching a new goroutine for each. Yet, it is capable of handling tens of thousands of requests per second for a typical request load (benchmark source).

So all-in-all, just don’t write “bad code”. The goroutine scheduler is not (fully) preemptive, so make sure your goroutines don’t do senseless computation that would prevent the scheduler to run other goroutines. Typically, system calls, IO operators and blocking operations (e.g. sending on / receiving from channels) are good yielding points. Many code do these under the hood even if you don’t know it, so most code does not cause a problem. If one of your goroutines must do extensive calculations, you can always call runtime.Gosched() to yield the processor, allowing other goroutines to run.

Answered By – icza

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.