Loading the lesson...
In the print dialog, choose "Save as PDF" as the destination.
Operating Systems 1 - Week 07 Lab
Creating threads, the race conditions they cause, the lock that prevents them, and the ThreadPool that reuses them.
Program
static instructions on disk
Process
owns memory and resources
Thread
smallest unit of execution
Thread myThread = new Thread(PrintNumbers);
myThread.Start();
myThread.Join(); // wait for it to finishStart begins execution, and Join blocks the caller until it ends. That pair is the fork-join pattern.| Style | How the work runs |
|---|---|
| Synchronous | sequentially, each operation finishing before the next begins |
| Asynchronous | concurrently, a later one starting before an earlier one finishes |
Thread pingThread = new Thread(Ping);
Thread pongThread = new Thread(Pong);
pingThread.IsBackground = true;
pongThread.IsBackground = true;
pingThread.Start();
pongThread.Start();
pingThread.Join();
pongThread.Join();Unstarted
created, not started
Running
after Start
WaitSleepJoin
blocked on Sleep or Join
Stopped
the method returned
Abort is deprecated, and a thread can never be started twice011 back, and the expected 2 is loststatic void IncrementCounter(object state)
{
// WITHOUT LOCK - race condition can occur
for (int i = 0; i < 100; i++) counter++;
}0 rarely produces 0.static object lockObject = new object();
lock (lockObject)
{
for (int i = 0; i < 100; i++) counter++;
}ThreadPool.SetMaxThreads(50, 50);
ThreadPool.QueueUserWorkItem(IncrementCounter);QueueUserWorkItem hands work to whichever pooled thread is free| ThreadPool | Manual thread | |
|---|---|---|
| Creation cost | low, threads are reused | high, each one is fresh |
| Control | limited | full, over lifecycle and priority |
| Suits | short tasks | long-running operations |
| Cleanup | automatic | yours to handle |
long partialSum = 0;
for (int i = start; i <= end; i++) partialSum += i;
lock (lockObject) { totalSum += partialSum; }4000 ms single-threaded1200 ms across four threadsAbortStart begins a thread and Join waits for it, which together are fork-joinlock protects the critical sectionMahmoud Abas|Operating System Lab - Week 7