Threads and shared state
Threads and shared state
A thread is an execution path scheduled by the runtime and operating system. A Task represents work or eventual completion and does not imply a dedicated thread. When workers share mutable state, correctness must not depend on accidental scheduling. A race occurs when the result depends on timing or ordering; the read, calculation, and write of an ordinary increment are separate steps. Synchronization also constrains visibility and ordering of memory operations.
Baseline: .NET 10 / C# 14; inherited SDK candidate 10.0.404. Each example is an independent console project. Outputs are reasoned, not executed. The native-library example is Linux-only and requires the included C source.
Start a thread and observe completion
A dedicated thread computes a small result. Join establishes completion before reading the result; use a finite timeout as a lab guard.
using System;using System.Threading;int result = 0;var worker = new Thread(() => result = 6 * 7) { IsBackground = true };worker.Start();if (!worker.Join(TimeSpan.FromSeconds(10))) throw new TimeoutException("Worker did not finish");Console.WriteLine(result);After successful Join, the main thread observes the completed worker result. The timeout is a guard, not a performance assertion. If the worker could throw, design an explicit exception reporting path.
Expected observation (reasoned, not executed):
42Model a lost update without racing the runtime
This single-thread model explicitly chooses a possible interleaving of two unsynchronized increments. It is not a live race reproduction.
using System;int count = 0;int workerARead = count;int workerBRead = count;count = workerARead + 1;count = workerBRead + 1;Console.WriteLine(count);Both workers read zero and later store one. Two intended increments yield one in this model. Real unsynchronized execution may also produce two; no specific race outcome is guaranteed.
Expected observation (reasoned, not executed):
1Avoid sharing the accumulator
Return a local result from each CPU-bound task, then combine the results after completion. No assumptions about the order tasks run.
using System;using System.Threading.Tasks;Task<int> first = Task.Run(() => 3 * 4);Task<int> second = Task.Run(() => 5 * 6);int[] parts = await Task.WhenAll(first, second);Console.WriteLine(parts[0] + parts[1]);Task.WhenAll yields results in input-task order after successful completion. Task.Run schedules work to the thread pool; it is not a promise of simultaneous execution. Asynchronous I/O normally should not need Task.Run just to await it.
Expected observation (reasoned, not executed):
42Common mistakes and design trade-offs
Do not use Thread.Sleep as a visibility or completion protocol. A volatile field does not make count++ atomic. Thread-safe collection operations do not make a check-then-update sequence atomic. Avoid blocking many thread-pool workers on synchronous waits, which can delay other work. Deadlock involves a cycle or other unsatisfiable wait; contention is competition for a resource, not necessarily deadlock.
Apply the concept
Trace two workers incrementing a counter from 10. Show a lost-update schedule and a schedule that produces 12. Then propose a design with worker-local counts and a final merge.
Check your work: Lost update: A and B both read 10, both write 11. Sequential schedule: A reads 10 and writes 11; B reads 11 and writes 12. Local results combined after completion eliminate shared increments.
Continue with the next planned lesson in this track. For authoritative details, consult the linked source evidence and the reference drafts. All examples remain pending compiler and runtime verification.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Threads and shared state — knowledge check
Apply the lesson concepts to the following scenarios.
What does Task represent?
Why can count++ lose an update?
What does a successful Join establish?
What makes local results useful?
What is the role of Thread.Sleep in synchronization?