0% completed
Concurrency, Parallelism, and Multithreading
On This Page
Know the Vocabulary
Part 1: The Ticket Server Puzzle
What One Request Does
Part 2: What Concurrency Is
The Definition
How One Core Takes Turns
Who Decides Which Thread Runs
What Concurrency Is Not
Part 3: What Parallelism Is
The Definition
How Many Can Run at the Same Instant
What Parallelism Is Not
Part 4: Seeing Both in Code
The Code
What the Results Show
Two Details in the Code
Part 5: Three Ways to Keep Many Requests in Progress
Where Multithreading Fits
FAQs
Key Takeaways
Check Your Understanding
Know the Vocabulary
This lesson uses the terms below many times. Read them once now, and come back here when a later section needs one.
- Request: One message from a fan's browser to the server, such as a request for the seat map. The work the server does for it is a task.
- Core: One part of the processor that runs one thread at a time.
- Logical processor: One core as the operating system counts it. It runs one thread at a time. Many processors run two threads on each physical core, so they report twice as many logical processors as physical cores.
- Process: A running program. Each process has its own memory, which other processes cannot read.
- Thread: One path of work inside a process. All the threads of one process share its memory.
- Scheduler: The part of the operating system that decides which thread runs on each core, and for how long.
- Time slice: The short time a thread may run on a core before the scheduler can give that core to another thread.
- Concurrency: Having several tasks in progress during the same period of time. They may take turns on one core, or they may run on several cores.
- Parallelism: Running several tasks at the same instant, each on its own core.
- Multithreading: Running several threads inside one process.
- Event loop: One thread that runs many tasks by switching to another task whenever the current one must wait.
Part 1: The Ticket Server Puzzle
The concert ticket website in this course is still young. Its engineering team runs the ticket server on one machine with 4 cores. Each core runs one thread at a time, so the machine runs at most 4 threads at any instant.
At 10:00, the sale opens. The team's monitor shows 2,000 fan requests in progress on the server at the same moment. Fans are loading the seat map, clicking "Buy," and paying. Yet the server answers every one of these requests.
How can 4 cores serve 2,000 requests at once? This lesson answers that question. The answer has two parts, concurrency and parallelism. The difference between them is the base of this whole course.
What One Request Does
Follow one request to see where its time goes. A fan opens the seat map, and the server handles the request in three steps:
-
Read the request. The server reads what the fan asked for. This takes about 1 ms of computing on a core.
-
Ask the database. The server asks the database for the free seats. The database runs on a separate machine, so the answer takes about 50 ms to come back. During those 50 ms, the server only waits.
-
Build the page. The server turns the answer into a page for the fan. This takes about 1 ms of computing.
The request takes about 52 ms in total. Yet it needs a core for only about 2 ms of that time. For the other 50 ms, it waits for the database and needs no core at all.
If the core stayed idle during that wait, it would waste 50 ms. Instead, it can run other requests in that time. Each request computes for about 2 ms. So during one 50 ms wait, one core can do the computing for about 25 other requests.
That is the key to the puzzle. At any moment, most of the 2,000 requests are waiting. Some wait for the database, some wait for the payment provider, and some wait for the fan's slow phone network. Only the few requests that are computing need a core.
Part 2: What Concurrency Is
The Definition
Concurrency means that several tasks are in progress during the same period of time. Each task has started and has not yet finished. The tasks do not need to run at the same instant. They can take turns on one core, and each one makes some progress before the next one gets the core.
A kitchen with one cook works the same way. The cook is making pasta, soup, and a salad. While the pasta boils, the cook chops the salad. While the soup heats up, the cook drains the pasta. All three dishes are in progress, yet the cook does one thing at a time. In a server, the cook is a core, and each dish is a request. Boiling and heating are the waits for the database, when the dish needs no cook.
Concurrency is about how the work is organized. The server splits its work into many tasks that can be in progress together. Whether two of them also run at the same instant depends on the machine.
How One Core Takes Turns
Picture one core and three requests, A, B, and C. Each request computes, waits for the database, and then computes again.
Step 1: The core runs A. Request A reads what its fan asked for. Requests B and C have arrived, but they wait for the core.
Step 2: A waits, and the core runs B. Request A sends its question to the database and waits for the answer. A waiting request needs no core, so the core moves on to B. Request C still waits for the core.
Step 3: B waits, and the core runs C. Request B also waits for the database now. The core runs C.
Step 4: The core runs A again. The answer for A has arrived. Request C now waits for the database, so the core goes back to A, which builds its page and finishes.
The diagram below shows the same four steps over time. The bottom row shows which request the core runs at each moment.
Notice that all three requests were in progress during all four steps. Yet the core never ran two of them at the same instant. That is concurrency without parallelism.
Who Decides Which Thread Runs
On a real server, each request usually runs on a thread, and the scheduler decides which thread gets a core. A thread that starts to wait for the database gives up its core at once. A thread that computes for a long time can be stopped when its time slice ends. Then a thread that waits for a core gets a turn. Stopping a running thread this way is called preemption.
Moving a core from one thread to another is called a context switch. Each switch costs a little time. The core must save the state of one thread and load the state of the next. The Thread Life Cycle and Scheduling lesson covers both ideas in detail.
What Concurrency Is Not
Concurrency is not the same as parallelism. One core can keep many tasks in progress, as the steps above showed, without ever running two at the same instant.
Concurrency does not make one task faster either. Request A still needs its 2 ms of computing and its 50 ms wait. Concurrency fills the waiting time with other work, so more requests finish each second.
Concurrency is not the same as threads. Threads are one way to have several tasks in progress, and Part 5 shows two other ways.
Part 3: What Parallelism Is
The Definition
Parallelism means that several tasks run at the same instant, each on its own core. It needs hardware. A machine with 4 cores can run at most 4 threads in parallel, no matter how many threads the program creates.
Go back to the ticket server at 10:00. All 2,000 requests are in progress, so the server is concurrent. At any instant, at most 4 of them compute on the 4 cores, so the server is also parallel. The other requests wait for the database, for the payment provider, or for a free core.
The diagram below shows the server at one instant during the sale.
The table below puts the two ideas side by side.
| Question | Concurrency | Parallelism |
|---|---|---|
| What does it mean? | Several tasks are in progress during the same period | Several tasks run at the same instant |
| Does it need more than one core? | No | Yes |
| What is it about? | How the work is organized | How the work is run |
| What does it gain? | It uses waiting time for other work | It finishes computing work sooner |
| What does the ticket server show? | 2,000 requests in progress | At most 4 requests computing |
Tasks that run in parallel are always concurrent too, because both are in progress at that instant. The opposite is not true. Concurrent tasks run in parallel only when several cores are free and the tasks are computing on them.
How Many Can Run at the Same Instant
Each language has a call that tells a program how many threads the machine can run at the same instant:
| <span style="white-space:nowrap">Language</span> | <span style="white-space:nowrap">Call</span> |
|---|---|
| Java | Runtime.getRuntime().availableProcessors() |
| Python | <span style="white-space:nowrap">os.cpu_count()</span> |
| C++ | std::thread::hardware_concurrency() |
| C# | <span style="white-space:nowrap">Environment.ProcessorCount</span> |
These calls count logical processors, not physical cores. The C++ call can also return 0 when it cannot tell. Many processors let one physical core run two threads at once. The two threads share the parts of that core. So together they usually run much less than twice as fast as one thread. The test machine for this lesson has 8 physical cores, and all four calls reported 16.
What Parallelism Is Not
Parallelism does not speed up waiting. A database answer that takes 50 ms takes 50 ms on any number of cores. More cores help only with the computing part.
Parallelism is not automatic in every language. In the standard Python build, only one thread at a time can run Python code. A lock inside Python, called the Global Interpreter Lock (GIL), enforces this rule. Python threads still take turns, so they are concurrent. But they do not compute in parallel. Newer Python versions also offer an optional build without the GIL.
Part 4: Seeing Both in Code
The Code
The program below serves fans in two ways. First, the main thread serves all the fans one after another. Then, each fan gets a thread of its own. The program does this for two kinds of requests:
- Waiting requests. Each of 20 fans waits 50 ms for the database and computes almost nothing. A 50 ms sleep stands in for the database.
- Computing requests. Each of 4 fans only computes a ticket code, with no waiting. This takes about 90 ms per request on the test machine.
For each run, the program prints the most requests that were in progress at the same time, and the total time. It also prints the number of logical processors.
Before you look at the results, predict what Python does with the 4 computing requests.
The program runs 4 requests that only compute, with no waiting. First one thread runs them one after another, and then each request gets its own thread. The machine has 16 logical processors. What happens with the 4 threads in the standard Python build?
Here is one real run of the Java version on one test machine:
This machine has 16 logical processors 20 fans, each request waits 50 ms for the database One thread, waiting : 20 requests, at most 1 in progress, 1230 ms 20 threads, waiting : 20 requests, at most 20 in progress, 50 ms 4 fans, each request only computes, with no waiting One thread, computing: 4 requests, at most 1 in progress, 374 ms 4 threads, computing : 4 requests, at most 4 in progress, 100 ms
And here is one real run of the Python version on the same machine:
This machine has 16 logical processors 20 fans, each request waits 50 ms for the database One thread, waiting : 20 requests, at most 1 in progress, 1002 ms 20 threads, waiting : 20 requests, at most 20 in progress, 51 ms 4 fans, each request only computes, with no waiting One thread, computing: 4 requests, at most 1 in progress, 349 ms 4 threads, computing : 4 requests, at most 4 in progress, 385 ms
What the Results Show
Waiting requests overlap on any machine. With one thread, the 20 requests took turns, and the total was 20 waits in a row. With 20 threads, all 20 requests were in progress at once, and the total fell to about one wait. That is 20 requests in progress on a machine with 16 logical processors. It works because a waiting thread needs no core.
Computing requests need cores. In Java, the 4 threads finished in 100 ms instead of 374 ms, because they computed in parallel on 4 cores. C++ and C# did the same. C++ took 93 to 99 ms instead of 352 to 379 ms. C# took 92 to 97 ms instead of 365 to 374 ms.
Python showed concurrency without parallelism. Its 4 threads were all in progress at once, just as in Java. Yet they took 385 ms against 349 ms for one thread. In a second run, they took 347 ms against 349 ms. The GIL let only one thread compute at a time, so the threads only took turns. In the first run, switching between them even cost a little extra time.
Notice that "at most 4 in progress" was the same in every language. Being in progress together is concurrency, and it says nothing about running at the same instant. Only the total time showed whether the threads ran in parallel.
Notice also the one-thread waiting times. Python took about 1,000 ms, which is 20 waits of 50 ms. Java, C++, and C# took about 1,240 ms. On that test machine, each 50 ms sleep in those three languages lasted about 62 ms.
Two Details in the Code
Each thread first waits for a start signal, so that all the fans begin together. That is what happens when a sale opens at 10:00. The Condition Variables lesson shows how a signal like this works.
Each request also writes its start and end times into its own slot of an array. No two threads ever change the same data, so the program needs no lock. When threads do change the same data, results can go wrong, as the Race Conditions and Critical Sections lesson shows.
Part 5: Three Ways to Keep Many Requests in Progress
Threads are one way to make a server concurrent. Real servers use three main ways, and many combine them.
Several processes. The server runs several copies of the program, and each copy is a process. The operating system can run the copies on different cores at the same instant. Each process has its own memory, so a bug in one copy cannot change the data of another. But sharing data, such as the seats left, then needs extra work. The processes must use a database or send messages to each other. Many Python web servers still run several processes, often one or more per core. Each process has its own GIL, so the processes can compute on several cores at once.
Several threads in one process. This is multithreading. The server runs one process with many threads, and each thread can handle one request. The threads share one memory, so they can all read the seat map directly. On a machine with several cores, the threads can also run in parallel. Sharing memory is both the strength and the risk of threads. Two threads that change the same data at the same moment can corrupt it. A crash in one thread can also end the whole process, with every thread in it.
An event loop. The server runs one thread that holds many tasks. When a task must wait for the database, it hands control back to the loop. The loop then runs another task that is ready. Node.js works this way, and so does Python's asyncio. One loop uses one core, so it gives concurrency without parallelism.
The table below compares the three ways.
| <span style="white-space:nowrap">Question</span> | Several processes | Several threads | Event loop |
|---|---|---|---|
| Is memory shared? | No, each process has its own | Yes, all threads share it | Yes, but only one task runs at a time |
| Can work run on several cores? | Yes | Yes, except Python code in the standard build | No, one loop uses one core |
| What does one more cost? | The most: a new process with its own memory | Some memory and setup time | The least: a small object per task |
| What is the main risk? | Sharing data is slow and takes extra work | Threads can change shared data at the same time | One task that computes for a long time stops every other task |
Real servers often mix these ways. The Nginx web server runs a few processes, and each process runs its own event loop. Many Java servers run one process with a group of threads that handle requests.
Where Multithreading Fits
Multithreading gives both ideas of this lesson. On one core, threads take turns and keep many tasks in progress, which is concurrency. On several cores, threads also run at the same instant, which is parallelism.
Threads are not free, though. Each thread needs its own stack, a block of memory for its function calls. On many systems, each stack reserves about 1 MB. Creating and ending a thread also takes time. So a server with 2,000 requests rarely starts 2,000 new threads. It keeps a fixed group of threads alive and gives each one many requests, one after another. The Thread Pools and Executors lesson shows how that works.
This course uses threads in Java, Python, C++, and C#. Coding interviews about concurrency are mostly about threads, and about the shared data that makes them hard.
FAQs
Q: Can a program with only one thread be concurrent?
Yes. An event loop keeps many tasks in progress on one thread. It switches to another task whenever the current task must wait. It is concurrent, but it is not parallel.
Q: Can a machine with one core run threads in parallel?
No. One core runs one thread at a time. Its threads can still be concurrent, because the scheduler gives each one short turns on the core.
Q: Do more threads always make a program faster?
No. Threads help with waiting on any machine. For computing, they help only up to the number of cores. They do not help at all for Python code in the standard build. Every thread also costs memory and setup time. The Why Concurrency Matters lesson measures these limits.
Q: Are Python threads useful at all, then?
Yes. A Python thread releases the GIL while it waits for a database, a network, or a sleep. In the demo, Python served 20 waiting requests in 51 ms with 20 threads, and in 1,002 ms with one thread. For heavy computing, Python programs use several processes instead.
Q: Is async code the same as multithreading?
No. In Python and JavaScript, async code runs on an event loop with one thread. C# is different. Its async code can continue on another thread after a wait, using threads from a shared pool. So in C#, async code can still run on several threads.
Key Takeaways
- Concurrency means several tasks are in progress during the same period. They can take turns on one core. The ticket server keeps 2,000 requests in progress on 4 cores.
- Parallelism means several tasks run at the same instant. It needs one core per task, so 4 cores run at most 4 threads at once.
- Waiting needs no core. In the demo, 20 threads kept 20 waiting requests in progress on 16 logical processors, and finished in about one wait.
- Computing needs cores. Java, C++, and C# ran 4 computing requests in parallel, almost 4 times faster. Standard Python ran them concurrently, but not in parallel, and gained nothing.
- Core-count calls return logical processors. The test machine has 8 physical cores, and all four languages reported 16.
- Processes, threads, and event loops are three ways to be concurrent. Threads share memory, which makes sharing data easy and also makes it risky.
- In a coding interview, define concurrency and parallelism in one sentence each, and give an example of concurrency on one core. Then say whether the task waits or computes, because that decides whether threads, processes, or an event loop fits best.
This lesson showed what concurrency is. The next lesson, Why Concurrency Matters, shows what a slow ticket server gains from it. It also shows what limits that gain.
Check Your Understanding
1. A server has one core and keeps 50 requests in progress. Is it concurrent, parallel, or both?
<details> <summary>Show answer</summary>It is concurrent, but not parallel. The 50 requests are in progress during the same period, so the server is concurrent. With one core, only one of them runs at any instant, so nothing runs in parallel.
</details>2. A database query takes 50 ms. Does moving the server from 4 cores to 16 cores make each query faster?
<details> <summary>Show answer</summary>No. During the query, the server only waits, and waiting needs no core. More cores help only with the computing part of each request.
</details>3. Four Python threads each compute for 100 ms, using the standard Python build. About how long do they take in total?
<details> <summary>Show answer</summary>About 400 ms, the same as one thread doing all four. The GIL lets only one thread run Python code at a time. The threads are concurrent, so they take turns, but they do not compute in parallel.
</details>4. A Java program calls availableProcessors() and gets 16. Does the machine have 16 physical cores?
Not necessarily. The call counts logical processors. On many processors, each physical core runs two threads. So 16 logical processors can mean 8 physical cores, as on this lesson's test machine.
</details>Flashcards Review
What is concurrency?
Reading Progress
0%
On This Page
Know the Vocabulary
Part 1: The Ticket Server Puzzle
What One Request Does
Part 2: What Concurrency Is
The Definition
How One Core Takes Turns
Who Decides Which Thread Runs
What Concurrency Is Not
Part 3: What Parallelism Is
The Definition
How Many Can Run at the Same Instant
What Parallelism Is Not
Part 4: Seeing Both in Code
The Code
What the Results Show
Two Details in the Code
Part 5: Three Ways to Keep Many Requests in Progress
Where Multithreading Fits
FAQs
Key Takeaways
Check Your Understanding