ENES

Concurrency

Structuring a program so several tasks can be in progress at the same time.

Two tasks interleaving their steps on one timeline while one waits for the network, and two tasks updating a shared counter at the same time

Concurrency means a program is dealing with several tasks whose lifetimes overlap: while one waits for a file, a database or the network, another can make progress. A web server handling thousands of visitors, or an app that keeps scrolling smoothly while it downloads images, depends on it. The usual tools are threads, separate processes, and async/await, which lets a single thread pause a task at each slow step and switch to another.

It is related to, but not the same as, parallelism. Concurrency is about structure: juggling many tasks, even on a single CPU core by switching between them. Parallelism is about execution: literally running things at the same instant on several cores. A concurrent program can run in parallel if the hardware allows it, but it does not have to. Go's co-creator Rob Pike summed it up as "concurrency is about dealing with lots of things at once; parallelism is about doing lots of things at once".

The hard part is shared data. If two tasks read a bank balance of 100, each adds 50, and each writes back its result, the balance ends at 150 instead of 200: a race condition, where the result depends on who happened to go first. Programmers prevent it with locks (only one task may touch the data at a time), atomic operations, or designs that avoid sharing at all, like passing messages. Overdo the locks and you risk a deadlock, where two tasks each wait forever for the other's lock. These bugs are notorious because they may appear once in a million runs.

Keep in mind

Go deeper

Related terms

More in Software