Concurrency
Конкурентность
A program runs tasks concurrently when it can make progress on one task before another one finishes. The tasks do not have to run at the exact same time.
What concurrency looks like
Suppose a web server receives two requests. The first needs data from a database, so the server has to wait for a reply. Rather than leaving the second request untouched, the server can start handling it during that wait. Both requests are now in progress, even if only one is executing code on the CPU at any given instant.
That distinction separates concurrency from parallelism. A single CPU core can support concurrent work by switching between tasks. Parallel execution means that work actually runs at the same time, for example on separate cores. A server can use both: several threads can run in parallel, and each can handle multiple requests over time.
Who decides what runs next?
With OS threads, the operating system can pause one thread and let another run without the first thread explicitly yielding. In a single-threaded async runtime, tasks generally yield control at suspension points. When a task awaits a result that isn't ready, the event loop can resume another task that is ready. Calling a blocking function or running a long computation on that thread prevents the event loop from doing so.
Example: overlap two waits
async function loadPageData() {
const profileRequest = fetch('/api/profile');
const settingsRequest = fetch('/api/settings');
const [profile, settings] = await Promise.all([
profileRequest,
settingsRequest,
]);
return { profile, settings }; // Response objects
}
Each fetch call starts a request without waiting for the other response. Promise.all doesn't launch the requests; it waits for both promises to fulfill, or rejects if either rejects. The result array follows the input order, not the order in which the responses arrive. By contrast, if you await the first fetch before calling the second, the waits can't overlap.
What can go wrong?
A single thread doesn't rule out race conditions. Imagine two tasks reading the same cached value, awaiting some work, and then writing an update based on what they read. Both might read the old value before either writes, so the second write overwrites the first. Depending on where the state lives, a fix might be to keep the read and write together without yielding, serialize updates with a lock, or use an atomic update provided by the database.
Concurrency also doesn't make every workload faster. It helps a server keep doing useful work while requests wait on I/O, but starting thousands of operations at once can exhaust a connection pool. A limit on in-flight operations lets you overlap waits without overwhelming the resource they share.
In an interview
When asked whether concurrent code is correct, walk through a specific ordering of events. Identify where a task can yield or be interrupted, what another task can change in that gap, and which guarantee your proposed fix provides.