System Design · Concept Library · Free article
Threads Share More Than Work
What do threads share? Follow two image workers through separate stacks, shared memory and a scratch-buffer race.
Threads are execution paths inside one process. They share the process address space and open resources, while each thread keeps execution state such as its stack and registers. Shared memory makes communication direct, but mutable data can be corrupted by an unlucky interleaving. Private per-job state or synchronization can preserve the result.
One process can have several execution paths
A thread is one sequence of instructions running inside a process. Worker A follows the instructions for the thumbnail job. Worker B follows the instructions for the index job. Each thread has its own position in the program.
Suppose A pauses halfway through a loop. B can run while A is paused. When A gets another turn, A continues from its saved position. A does not start the loop again, and A does not continue from B's position.
Both jobs can make progress during the same period. That is concurrency. One CPU core can provide concurrency by taking turns between the threads. If two cores execute the threads at the same instant, the work is also parallel. Creating two threads does not guarantee that two cores will run them together.
The process supplies the memory that both threads can address. An address space is the set of memory addresses available to that process. When A and B hold references to the same array, those references lead to the same storage. A write changes that storage; a later properly coordinated read by B can read the changed value. There is no need to send a separate copy of the array just to make it reachable by B.
Imagine that both workers call transform(input). A is processing one image and B is processing another. For example, A might reach i = 7 while B is still at i = 2. These are two invocations of the function, so each invocation needs its own loop position.
A call stack records active function calls and the information needed to return from them. Each thread has its own stack. A's call to transform belongs to A's stack. B's call belongs to B's stack. Registers hold values that the CPU is currently using, including execution-position information. When a thread pauses, its saved register state lets it resume with its own values. This does not mean every thread has a permanently reserved set of physical CPU registers.
Now give both calls the same scratch array. Scratch storage holds an intermediate value that a calculation still needs. The reference variable in A's call and the reference variable in B's call can be separate while both refer to this one array. Copying a reference does not copy the array.
The heap holds dynamically allocated objects, such as an array that remains alive beyond the function call that created it. Threads in this model share access to the process heap. A heap object can still belong to one job by program design: only that job receives a reference and uses it. Private scratch in this lesson means separate storage for each job, with no cross-job access. It can be allocated on the stack or the heap.
A separate stack is also not an operating-system protection boundary. Both stacks lie in the same process address space. If A passes B a valid pointer to one of A's live stack objects, B can access that object. A must keep the object alive for as long as B needs it, and their accesses still need coordination.
The next machine uses one pixel per job so each operation fits on screen. A halves 40 to make 20. B halves 90 to make 45. Each call has its own input and place in the instructions. Give A a turn, enter its call, then switch to B. The arithmetic is a small stand-in for work inside the image pipeline.
Enable JavaScript to compare the two choices in the compact concept diagram. The worked examples explain the same process boundary, scratch ownership, CPU schedule or pending-I/O consequence without requiring the interactive.
Threads also share open resources. A file descriptor is a number a process uses to refer to an open resource, such as a file. The process keeps a table of these descriptors. Creating another thread does not create an independent table. A process ID identifies the containing process; the threads have their own thread identities.
| Resource or state | Shared by threads in one process? | Why it matters here |
|---|---|---|
| Heap objects and global data | Yes | Both workers can reach the shared scratch object |
| Open file descriptors | Yes | Either thread can use a process-opened resource, subject to API rules |
| Stack and automatic call state | Distinct per thread, not memory-protected | Each worker can pause inside a different function call |
| Register and instruction state | No | Each worker resumes its own execution |
| Process ID and address space | Yes | The threads remain inside one process boundary |
The wrong result can come from individually valid steps
Use one pixel from each job so the values fit on screen. A starts with 40; B starts with 90. Each calls transform(input), which halves this pixel. A should produce 20; B should produce 45. This arithmetic stands in for work inside an image pipeline. It is not a complete thumbnail or indexing algorithm. The scratch cell has room for one value. Each worker first writes its value to scratch, then reads scratch to produce its own output.
A writes 20. The cell now holds 20, but A has not copied that value to its output yet. A pauses.
B runs next. B writes 45 into the same cell. The cell now holds 45. A's temporary value has been overwritten.
A resumes at its read. A reads the current contents of the cell, which are 45. The read succeeds, but A produces 45 instead of 20. A's saved loop position was correct. The shared data A relied on had changed.
This mix of steps is an interleaving. Each job keeps its own instruction order, while their steps are mixed together. The failure needs no simultaneous writes: A and B can take these turns on one core. A test that runs A all the way through before B may never expose the mistake.
| Step | Executing job | scratch holds | Consequence |
|---|---|---|---|
| 1 | A writes its transformed pixel | 20 | A has not consumed it yet |
| 2 | B writes its transformed pixel | 45 | A's intermediate value is overwritten |
| 3 | A reads for its output | 45 | A emits 45 instead of 20 |
| 4 | B reads for its output | 45 | B happens to be correct |
Try Shared cell below. Follow the suggested turns through A's write, B's overwrite and the completed outputs. Then choose Separate cells and compare. Separate cells let A read 20 and B read 45, even when both jobs are in progress. The repair changes where the temporary data lives.
Enable JavaScript to compare the two choices in the compact concept diagram. The worked examples explain the same process boundary, scratch ownership, CPU schedule or pending-I/O consequence without requiring the interactive.
Sometimes the jobs really do need to use one shared object. A mutex is a lock that allows one holder at a time. A takes the lock before writing scratch. A keeps the lock while reading scratch into its output. Only after that read does A release the lock, allowing B to use scratch.
The protected sequence is called a critical section. Every thread accessing scratch must follow the same locking rule. The lock does not make the memory physically inaccessible to a thread that ignores the rule. Locking only the final output write would leave B free to overwrite scratch before A reads it.
One worker can also finish A before starting B. That removes this interleaving by putting the entire jobs in sequence. A mutex only puts the protected region in sequence. Separate scratch avoids sharing the intermediate value at all. The first guided experiment asks for separate scratch; the second keeps shared scratch and asks you to protect it.
Enable JavaScript to compare the two choices in the compact concept diagram. The worked examples explain the same process boundary, scratch ownership, CPU schedule or pending-I/O consequence without requiring the interactive.
More threads do not create more CPU or device capacity
A worker pool limits how many workers can take jobs at once. Here there are only two jobs. A pool with eight slots cannot give six idle slots useful work. Reducing that pool to two slots preserves room for both jobs.
If the jobs spend their time computing, the available CPU cores limit how many threads can execute simultaneously. Eight runnable threads on two cores still have to take turns. If a worker instead waits for a device, another worker may be able to use the CPU during that wait. Additional workers help only while there is useful work and capacity to serve it.
Each real thread also needs resources such as stack memory. Threads also use the process file-descriptor table. More threads do not give the underlying device unlimited capacity. Shared resources need ownership rules too, including who may close them.
The lab assigns each worker slot an illustrative 64 KiB stack-address reservation. Eight slots reserve 512 KiB; two reserve 128 KiB. The experiment gives you a 128 KiB budget. These are declared teaching values, not an operating-system default or a measurement of resident RAM. The lab does not measure context-switch overhead or device throughput. Its fourth experiment is a capacity-budget check, not a claim that eight workers take a particular amount of extra time. The scheduling and I/O articles examine CPU turns and waiting separately.
A thread is not a separate process failure boundary
Suppose worker A performs an invalid memory access that triggers an unhandled native fault. The operating system can terminate the process. Worker B belongs to that process too, so B can lose its execution and the memory it still needs. A separate call stack did not give B a separate failure boundary.
The lab models this fault as a process crash. With both workers in one process, both jobs fail. Put B in a separate process and B retains its own memory, so B can finish after A's process fails. This contains A's modeled fault; it does not recover A's lost work.
An ordinary function error, a caught exception and a process-terminating fault are different events. A language runtime may handle an error without ending the process. This experiment deliberately selects the process-terminating case.
Separate processes also change communication. They need an explicit way to exchange data, such as the copied message in Program to Process. Choose that boundary when the failure isolation is worth the communication and resource costs. Threads remain useful when jobs can safely share a process.
Ungraded transfer checks
- If two threads call the same function, do they use one shared stack frame?
- No. Each invocation belongs to the calling thread's stack state, even though both execute the same program instructions.
- Does shared heap imply every object is unsafe?
- No. Immutable data can be read concurrently. Mutable data needs an ownership or synchronization rule when operations can overlap.
- Why does B wait at the mutex?
- Only one worker can hold the mutex at a time. B waits to use scratch until A has copied its value to output. That waiting preserves the result; the trace does not measure real lock overhead.
- Do eight threads guarantee eight-way parallelism?
- No. Parallel execution is bounded by runnable work, cores and other bottlenecks.
Your turn: repair four thread plans
Run each supplied failure before editing. The first experiment connects both workers to one cell. Watch A emit 45 instead of 20, pin that evidence, then connect B to another cell. The second experiment keeps one cell and asks both workers to follow the mutex rule. The third injects a fatal fault in A; move B and its scratch into another process. The fourth preserves both outputs while reducing stack reservations to 128 KiB. Each guide states its constraints, observations and repair hints.
Drag a reference from a worker to a scratch cell, or make the same edit in Inspect & edit. The canvas stays editable in portrait. Use its zoom and fit controls to inspect a process, and Results to compare current and pinned evidence. Run follows a deliberately overlapping schedule. Pause or use the named worker actions to choose a different order. No result is graded or saved to your account.
Threads in one process share its address space and open resources, while each thread keeps execution state such as its stack and registers. Sharing makes communication cheap, but unprotected mutable state and process-wide failure remain coupled.
Open The thread sharing workbench. Editable controls require JavaScript; the article and model limits remain readable here.
Sources and model limits
- Linux pthreads documentation lists process-wide and distinct per-thread attributes.
- C++ data races specifies why unsynchronized conflicting native accesses are not limited to this toy outcome.
- OSTEP locks explains mutual exclusion and critical sections.
- OSTEP concurrency introduction explains thread state, context switches and shared address spaces.
- The workbench lets you choose the turns of two jobs; Run uses a deliberately overlapping schedule. It does not model a language memory model, atomics, cache coherence or every failure-handling runtime.
Published by GOAT Engineer. Continue with CPU scheduling policies. Privacy policy · [Contact](mailto:[email protected]).
By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.