Software Engineer Encyclopedia
0%
Domain 01 · Computer Science & Programming Fundamentals · Topic 1.3

أنظمة التشغيل للـ .NET Backend Engineer

Operating Systems

الـ OS هو اللي بيشغّل كودك فعلاً: بيدّيك processes وthreads وذاكرة وملفات وI/O. الدرس ده بيركز على اللي بيأثر على الـ .NET في الـ production: concurrency، race conditions، deadlocks، thread pool، الذاكرة، ولينكس والـ containers.

  • Foundation
  • ~29 min read
  • 14 sections
  • 18 code examples
  • 13 diagrams
  • 11 questions
  • Priority L1 · Essential
  • .NET 10 · Linux (Ubuntu) · Windows

المتطلبات قبل ما تبدأ

مفيش متطلبات — ده أول الطريق. يكفي إنك كتبت كود بأي لغة قبل كده.

مستوى التعمق المطلوب

STRONG FOUNDATIONSPrioritize concurrency, memory, and synchronization for .NET.

01

Processes vs Threads وحياة كل منهم

Processes vs threads · process and thread lifecycle
Basics

الـ Process هو برنامج شغّال: ليه address space مستقل (ذاكرة خاصة)، وملفات مفتوحة، وهوية (PID). الـ Thread هو «خط تنفيذ» جوه الـ process. كل threads الـ process الواحدة بتشارك نفس الذاكرة (heap) بس كل thread ليه stack خاص ومسجلات (registers) خاصة.

Process A (PID 4120) Code + static data (shared by all threads) Heap — shared objects(needs synchronization!) Thread 1own stack Thread 2own stack Thread 3own stack Process B (PID 5871) Its own code + data Its own heap (cannot touch A's) Thread 1 isolated
الـ processes معزولة عن بعض. الـ threads جوه نفس الـ process بتشارك الـ heap والكود وتنفرد بالـ stack
ProcessThread
الذاكرةخاصة ومعزولة (حماية من الـ OS)مشتركة (heap) + stack خاص
تكلفة الإنشاءغالية (ملايين الـ cycles، mapping للذاكرة)أرخص بكتير (لكن مش مجانية: stack ~1MB)
التواصلIPC: pipes, sockets, shared memory, filesمتغيرات مشتركة (محتاجة synchronization)
لو حصل crashالـ process وحدها بتقعexception غير معالج في thread بيقع الـ process كلها
مثالتطبيقك + SQL Server + nginx = 3 processesكل request في Kestrel بيتنفذ على thread من الـ pool

دورة حياة الـ Thread

New Ready Running Terminated Waiting / Blocked dispatch preempted I/O, lock, sleep event done exit
حالات الـ thread: الـ scheduler هو اللي بينقله بين Ready و Running. أي انتظار (I/O أو lock) بينقله لـ Waiting
C#ThreadsVsProcesses.cs — threads share memory, processes don't
using System.Diagnostics;

// ---- THREADS: share the same variable ----
int shared = 0;
var t1 = new Thread(() => shared = 42);
t1.Start();
t1.Join();                                  // wait until the thread terminates
Console.WriteLine(shared);                  // 42  -> the thread wrote into OUR memory

Console.WriteLine($"Current PID={Environment.ProcessId}, managed thread id={Environment.CurrentManagedThreadId}");

// ---- PROCESSES: separate memory, communicate via streams ----
var psi = new ProcessStartInfo("dotnet", "--version")
{
    RedirectStandardOutput = true,
    UseShellExecute = false
};
using var child = Process.Start(psi)!;      // creates a NEW process with its own address space
string output = await child.StandardOutput.ReadToEndAsync();
await child.WaitForExitAsync();
Console.WriteLine($"child PID={child.Id} exit={child.ExitCode} output={output.Trim()}");

الشرح والتتبع

  1. new Thread(...) بيخلق thread جديد في نفس الـ process، وبيكتب مباشرة في المتغير shared (لأنه captured في heap). Join بيخلي الـ main thread يستنى (حالة Waiting) لحد ما الـ thread يخلص ويدخل Terminated.
  2. Process.Start بيطلب من الـ OS يعمل process جديدة (fork/exec على Linux، CreateProcess على Windows) ليها PID مختلف وذاكرة منفصلة. مفيش طريقة نكتب بها في متغيراتها، فالتواصل بس عن طريق stdout/stdin.
  3. في الـ backend: IIS/Kestrel بيشغّلوا الـ API في process، والـ threads جواها بتخدم الـ requests. والـ microservices كل واحدة process (غالباً container) منفصلة، وده بيدّي عزل للأعطال مقابل تكلفة التواصل الشبكي.
02

Scheduling و Context Switching

Scheduling concepts and context switching
Deep dive

عدد الـ threads أكبر بكتير من عدد الـ CPU cores. الـ Scheduler في الـ kernel هو اللي بيقرر مين يشتغل على أي core ولأد إيه. كل thread بياخد time slice (عادةً ملّي ثانية أو أقل)، وبعدين بيتعمله preempt (يتقاطع) ويدخل thread تاني. الـ OS بيستخدم preemptive multitasking: مش لازم الكود يتنازل بإرادته.

إيه اللي بيتحكم في الاختيار؟

  • الأولوية (priority) للـ thread/process.
  • Fairness: الكل ياخد نصيب (Linux CFS بيعتمد على «الوقت الافتراضي المستهلك»).
  • I/O-bound threads بتاخد أفضلية لأنها بتقعد تستنى كتير.
  • CPU affinity (تثبيت على cores).

Context Switch

الـ kernel بيحفظ حالة الـ thread الحالي (registers، program counter، stack pointer) وبيحمّل حالة thread تاني. التكلفة المباشرة: ميكرو ثواني. التكلفة غير المباشرة الأكبر: الـ CPU cache و TLB بيبقوا «بارد» للـ thread الجديد ⇒ cache misses.

time → Thread A running switch Thread B running switch Thread A again switch = save registers/PC/stack pointer of A → load B → (cache + TLB go cold) آلاف الـ threads = وقت كبير بيضيع في switching بدل الشغل الفعلي
Context switch: حفظ حالة thread A، تحميل حالة thread B. الوقت ده شغل مفيهوش أي منطق للتطبيق
C#ThreadCost.cs — more threads is not more speed
using System.Diagnostics;

// CPU-bound work: count primes in a range
static int CountPrimes(int from, int to)
{
    int count = 0;
    for (int n = Math.Max(2, from); n < to; n++)
    {
        bool prime = true;
        for (int d = 2; (long)d * d <= n; d++)
            if (n % d == 0) { prime = false; break; }
        if (prime) count++;
    }
    return count;
}

const int Max = 2_000_000;
Console.WriteLine($"Cores: {Environment.ProcessorCount}");

foreach (int workers in new[] { 1, Environment.ProcessorCount, Environment.ProcessorCount * 16 })
{
    var sw = Stopwatch.StartNew();
    int chunk = Max / workers;
    var tasks = Enumerable.Range(0, workers)
        .Select(i => Task.Factory.StartNew(
            () => CountPrimes(i * chunk, i == workers - 1 ? Max : (i + 1) * chunk),
            TaskCreationOptions.LongRunning))          // LongRunning = dedicated thread, not pool
        .ToArray();
    int total = (await Task.WhenAll(tasks)).Sum();
    Console.WriteLine($"{workers,4} threads -> {sw.ElapsedMilliseconds,5} ms (primes={total})");
}
// Typical shape on an 8-core machine:
//    1 threads ->  900 ms
//    8 threads ->  150 ms   <- near-linear speedup up to the number of cores
//  128 threads ->  160 ms   <- no gain; extra threads only add switching + memory
  1. الشغل CPU-bound: كل thread محتاج core بالكامل. الـ speedup بيقف عند عدد الـ cores.
  2. TaskCreationOptions.LongRunning بيخلي الـ Task يشتغل على thread مخصص مش من الـ thread pool عشان ما يخنقش الـ pool.
  3. الأرقام تقريبية وبتختلف بحسب الجهاز، لكن الشكل ثابت: تحسّن لحد عدد الـ cores، وبعدها لا تحسن (وأحياناً تراجع) بسبب الـ context switching وزيادة استهلاك الذاكرة (كل thread له stack).
  4. الدرس العملي: للشغل الـ CPU-bound استخدم عدد threads ≈ cores (Parallel.For بيعمل ده). للـ I/O-bound مش محتاج threads كتير أصلاً — محتاج async (قسم Thread Pools).
03

User Mode vs Kernel Mode و System Calls

User mode, kernel mode and system calls
Deep dive

المعالج بيشتغل في مستويين امتيازات. User mode (ring 3): كودك أنت و ‎.NET runtime، ومفيش وصول مباشر للهاردوير أو لذاكرة process تانية. Kernel mode (ring 0): نواة الـ OS، وليها كل الصلاحيات. ده بيحمي النظام: تطبيق بايظ ميقدرش يقفل الجهاز.

لو كودك عايز يعمل أي حاجة تخص مورد مشترك (يقرا ملف، يفتح socket، يطلب ذاكرة، يعمل thread)، بيعمل System Call: طلب للـ kernel عن طريق instruction خاصة. المعالج بيبدّل لـ kernel mode، الـ kernel ينفذ ويرجع النتيجة، وبعدين يرجع لـ user mode.

User mode your C# code .NET runtime / BCL libc / P/Invoke syscall (mode switch) Kernel mode VFS / file system page cache disk driver → hardware
كود ‎.NET بينادي File API ⇒ runtime بيعمل syscall (read) ⇒ kernel بيكلم الـ disk driver ويرجع البيانات
BashSee the syscalls behind a .NET call (Linux)
# Run a tiny program under strace and filter file-related syscalls
strace -f -e trace=openat,read,write,close -o trace.txt dotnet run --no-build
grep -E 'openat.*data.txt|read\(' trace.txt | head

# Typical lines:
# openat(AT_FDCWD, "/app/data.txt", O_RDONLY|O_CLOEXEC) = 12     <- File.OpenRead
# read(12, "hello world\n", 4096) = 12                          <- stream.Read
# close(12) = 0                                                  <- Dispose()
C#Syscalls.cs — cost of crossing into the kernel
using System.Diagnostics;

// Many tiny writes = many syscalls (unbuffered)
var sw = Stopwatch.StartNew();
using (var fs = new FileStream("tiny.bin", FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 1))   // 1 = effectively no buffering
{
    for (int i = 0; i < 200_000; i++) fs.WriteByte(1);          // ~200k write() syscalls
}
Console.WriteLine($"unbuffered: {sw.ElapsedMilliseconds} ms");

// Same data, one buffer = a handful of syscalls
sw.Restart();
File.WriteAllBytes("big.bin", new byte[200_000]);               // one write
Console.WriteLine($"single write: {sw.ElapsedMilliseconds} ms");
  1. كل WriteByte بدون buffering = syscall = انتقال user→kernel→user. الأرقام بتبقى أسوأ بكتير من نسخة الـ buffer الواحد (غالباً أضعاف عديدة).
  2. عشان كده الـ FileStream والـ StreamWriter بيستخدموا buffers (4KB افتراضياً) و BufferedStream، وعشان كده الـ batching مبدأ مهم: إكتب شوية كبيرة بدل ألف صغيرة (ينطبق على DB queries والـ network كمان).
  3. strace (أو dotnet-trace/perf) بيوريك الـ syscalls الفعلية وبيفسر ظواهر زي «ليه الـ app بتفتح ملف 10 آلاف مرة؟».
ربط بالـ Backend

أي عملية I/O (network، disk، DB connection) تعدي على syscall. وده سبب إن الـ context switch و buffering و batching مهمين في الأداء. وإن الـ container مش VM: الـ containers بتتشارك نفس الـ kernel مع الـ host، فالـ syscalls بتروح لنفس الـ kernel (وده بيفسر ليه seccomp profiles بتقيّدها لأمان الـ container).

04

Stack و Heap و Virtual Memory

Stack and heap · virtual memory and paging
Deep dive

Stack vs Heap

Stack

  • خاص بكل thread، بيشتغل LIFO.
  • بيخزن: method call frames، المتغيرات المحلية، value types المحلية، عناوين الرجوع.
  • الحجز والتحرير سريع جداً (تحريك pointer) ومن غير GC.
  • حجمه محدود (عادةً ~1MB لكل thread في ‎.NET على Windows، وأكبر على Linux). تجاوزه ⇒ StackOverflowException (process crash).

Heap

  • مشترك بين كل threads الـ process.
  • بيخزن: الـ objects (reference types)، arrays، strings.
  • الحجز أغلى والتحرير بيتم عن طريق Garbage Collector (managed heap).
  • الحجم محدود بالذاكرة المتاحة. تجاوزه ⇒ OutOfMemoryException.
Stack (thread 1) int count = 5 // value inline Order order = ──────┐ (return address) Managed heap (shared, GC-managed) Order object{ Id, Customer, Items → List } List<Item> (array of references)
reference type بيعيش في الـ heap والمتغير على الـ stack بيشاور عليه. value type محلي بيعيش على الـ stack مباشرة
C#StackHeap.cs — where does it live?
struct PointS { public int X, Y; }          // value type
class  PointC { public int X, Y; }          // reference type

static void Demo()
{
    int n = 5;                              // stack
    var ps = new PointS { X = 1, Y = 2 };   // stack (copied on assignment)
    var pc = new PointC { X = 1, Y = 2 };   // heap object; `pc` (the reference) is on the stack

    var copyS = ps; copyS.X = 99;           // changes the COPY only
    var copyC = pc; copyC.X = 99;           // both names point to the same object
    Console.WriteLine($"{ps.X} {pc.X}");    // 1 99

    Span<int> buffer = stackalloc int[128]; // 512 bytes on the stack: no GC allocation
    buffer[0] = n;
}

// Stack overflow: unbounded recursion
static int Boom(int n) => Boom(n + 1) + 1;  // each call adds a frame -> eventually crashes the process (not catchable)
  1. Value types (int, struct) بيتنسخوا عند الـ assignment، فتعديل النسخة مبيأثرش على الأصل. Reference types بيتنسخ فيها المؤشر بس، فالاتنين بيشاوروا على نفس الـ object.
  2. مقولة «value types دايماً على الـ stack» غير دقيقة: لو struct جوه class أو في array أو captured في lambda بيعيش جوه الـ heap مع الـ object اللي بيحويه.
  3. stackalloc مع Span<T> بيحجز على الـ stack من غير تحميل على الـ GC، مفيد للـ buffers الصغيرة المؤقتة (استخدمه بحذر وبأحجام صغيرة).
  4. الـ GC: كل allocation على الـ heap بيزيد ضغط الـ GC. الـ allocations الكتير في hot path بتعمل pauses. استخدم Span/ArrayPool/struct لما القياس يثبت إنها مشكلة.

Virtual Memory و Paging

كل process بتشوف عناوين «افتراضية» (virtual addresses) متصلة وخاصة بيها، ومش العناوين الفعلية في الـ RAM. الـ CPU (وحدة MMU) مع الـ OS بيترجموا العنوان الافتراضي لعنوان فعلي عن طريق page tables. الذاكرة متقسمة لـ pages (غالباً 4KB).

Process A (virtual) page 0 page 1 page 2 page 3 Page table (A) 0 → frame 71 → frame 22 → on disk (swap)3 → not allocated Physical RAM frame 2 (A.p1) frame 7 (A.p0) Disk / swapA.page 2 (evicted)
Virtual memory: كل process ليها خريطة خاصة. الصفحات ممكن تكون في الـ RAM أو على الـ disk (swap) أو لسه متحجزتش
الكود بيقرا من عنوان افتراضي ⇒ الـ MMU بيدور في الـ page table (وفي الـ TLB cache).
لو الصفحة موجودة في الـ RAM ⇒ يترجم العنوان ويكمل (سريع).
لو مش موجودة ⇒ Page Fault: الـ CPU بيرمي exception للـ kernel. لو الصفحة على الـ disk (swapped out) بيقراها (ميلي ثانية = ملايين الـ cycles) ويحدّث الـ page table، ولو الوصول غير قانوني ⇒ Segmentation fault/access violation.
لو الـ RAM مليانة، الـ kernel بيطرد صفحات قليلة الاستخدام (للـ swap أو يمسح اللي متعدلتش). كثرة الـ page faults ⇒ thrashing والنظام يتبطّأ جداً.
C#VirtualMemory.cs — memory-mapped file and working set
using System.Diagnostics;
using System.IO.MemoryMappedFiles;

// Memory-mapped file: the OS maps the file into virtual memory; pages load on demand (page faults)
File.WriteAllBytes("data.bin", new byte[100 * 1024 * 1024]);          // 100 MB file

using var mmf = MemoryMappedFile.CreateFromFile("data.bin", FileMode.Open);
using var view = mmf.CreateViewAccessor(0, 4096);                      // map only the first page
view.Write(0, 123);                                                    // touches page 0 -> loaded + marked dirty
Console.WriteLine(view.ReadInt32(0));                                  // 123

var p = Process.GetCurrentProcess();
Console.WriteLine($"Working set: {p.WorkingSet64 / 1024 / 1024} MB");     // physical RAM currently used
Console.WriteLine($"Virtual:     {p.VirtualMemorySize64 / 1024 / 1024} MB"); // address space reserved (can be much larger)
Console.WriteLine($"GC heap:     {GC.GetTotalMemory(false) / 1024 / 1024} MB");
  1. الـ memory-mapped file بيخلي الـ OS يحمّل الصفحات عند الحاجة فقط (demand paging)، فمقدرش تحمّل ملف 100MB كامل في الذاكرة بتكلفة قراءة بس اللي بتستخدمه.
  2. Working Set هو اللي في الـ RAM فعلاً دلوقتي. Virtual size هو الـ address space المحجوز وممكن يكون أكبر بكتير. الاتنين مختلفين عن حجم الـ GC heap.
  3. الـ container مع حد ذاكرة (مثلاً 512MB): لو الـ working set عدى الحد الـ kernel بيقتل الـ process (OOMKilled) بدل ما يعمل swap. الـ ‎.NET GC بيقرا الـ cgroup limit ويحدد الـ heap hard limit بنسبة (غالباً 75% من الـ limit) لتجنب ده.
05

Concurrency vs Parallelism

Concurrency vs parallelism
Basics

Concurrency

التعامل مع أكتر من حاجة في نفس الفترة، حتى لو على core واحد (بالتبديل بينهم). مشكلة تنظيم. مثال: سيرفر بيخدم 10,000 request متزامنين بعدد threads قليل لأن أغلبهم بيستنوا I/O.

Parallelism

التنفيذ الفعلي لأكتر من حاجة في نفس اللحظة على cores متعددة. مشكلة سرعة للشغل الـ CPU-bound. مثال: معالجة صور على 8 cores.

Concurrent (1 core, interleaved) ABABA Parallel (2 cores, simultaneous) core 1: task A core 2: task B
Concurrency: تبديل على core واحد. Parallelism: تنفيذ فعلي متزامن على cores مختلفة
C#ConcurrencyParallelism.cs — pick the tool by the kind of work
// CPU-bound => parallelism: split the work across cores
double[] data = Enumerable.Range(1, 5_000_000).Select(i => (double)i).ToArray();
double sum = 0;
var gate = new Lock();
Parallel.ForEach(
    System.Collections.Concurrent.Partitioner.Create(0, data.Length),
    () => 0.0,                                                    // thread-local accumulator
    (range, _, local) => { for (int i = range.Item1; i < range.Item2; i++) local += Math.Sqrt(data[i]); return local; },
    local => { lock (gate) sum += local; });                       // combine once per thread
Console.WriteLine(sum);

// I/O-bound => concurrency with async: no thread is blocked while waiting
using var http = new HttpClient();
string[] urls = ["https://example.com", "https://example.org", "https://example.net"];
var pages = await Task.WhenAll(urls.Select(u => http.GetStringAsync(u)));   // 3 requests in flight, 0 threads blocked
Console.WriteLine(pages.Sum(p => p.Length));
  1. الجزء الأول CPU-bound ⇒ Parallel.ForEach بيقسّم المدى على threads بعدد الـ cores. كل thread بيجمع في متغير محلي (local) ثم بنجمعهم تحت lock مرة واحدة لكل thread بدل lock لكل عنصر (ده بيتجنب الـ contention).
  2. الجزء التاني I/O-bound ⇒ Task.WhenAll بيبدأ 3 requests وبيستنى كلهم من غير ما يحجز thread واحد أثناء الانتظار.
  3. الخطأ الشائع: استخدام Task.Run(() => http.GetString(...)) للـ I/O (بيحجز thread من الـ pool طول فترة الانتظار)، أو استخدام async للـ CPU-bound وتوقع إنه هيسرّعه (async لا يخلق parallelism).
06

Race Conditions

Race conditions
Pitfalls

الـ Race Condition هو إن نتيجة البرنامج بتعتمد على توقيت تنفيذ threads متزامنة على بيانات مشتركة. أصعب الـ bugs لأنها مش بتظهر دايماً، وغالباً تختفي لما تعمل debug أو log (heisenbug).

Thread 1Thread 2counter in memory read counter → 5 read counter → 5 write 5 + 1 = 6 write 5 + 1 = 6 expected 7got 6 ❌ (one update lost)
Lost update: الـ counter++ مش عملية واحدة. thread 2 بيقرأ القيمة القديمة قبل ما thread 1 يكتب
C#RaceCondition.cs — reproduce it, then fix it three ways
// ❌ BUG: counter++ is read-modify-write, not atomic
int unsafeCounter = 0;
Parallel.For(0, 1_000_000, _ => { unsafeCounter++; });
Console.WriteLine($"unsafe:      {unsafeCounter:N0}");     // < 1,000,000 (varies every run)

// ✅ Fix 1: Interlocked — a single atomic CPU instruction (fastest for simple counters)
int atomicCounter = 0;
Parallel.For(0, 1_000_000, _ => { Interlocked.Increment(ref atomicCounter); });
Console.WriteLine($"interlocked: {atomicCounter:N0}");     // 1,000,000

// ✅ Fix 2: lock — protects a critical SECTION (needed when several variables change together)
int lockedCounter = 0;
var gate = new Lock();                                     // System.Threading.Lock (.NET 9+)
Parallel.For(0, 1_000_000, _ => { lock (gate) { lockedCounter++; } });
Console.WriteLine($"lock:        {lockedCounter:N0}");     // 1,000,000

// ✅ Fix 3: avoid sharing — thread-local partial results, combine at the end
long total = 0;
Parallel.For(0, 1_000_000, () => 0L, (i, _, local) => local + 1, local => Interlocked.Add(ref total, local));
Console.WriteLine($"no sharing:  {total:N0}");              // 1,000,000

الشرح

  1. unsafeCounter++ بيتحول لـ 3 خطوات: (1) read (2) add (3) write. thread تاني ممكن يدخل بينهم فيكتب فوق التحديث.
  2. Interlocked.Increment بتنفذ الـ 3 خطوات كـ atomic operation (CPU lock xadd). مناسب لـ counter واحد فقط.
  3. lock بيسمح لـ thread واحد في الوقت بدخول الـ critical section. بيشتغل لما التحديث يشمل أكتر من متغير (مثلاً رصيد + سجل العمليات).
  4. الحل الأفضل غالباً هو عدم المشاركة: كل thread يحسب لنفسه وبعدين نجمع. (أقل contention وأسرع).
  5. الأنواع الأخرى: check-then-act (if (!dict.ContainsKey(k)) dict[k] = v; على Dictionary مشترك) و lazy initialization غير آمنة. استخدم ConcurrentDictionary.GetOrAdd و Lazy<T>.
في ASP.NET Core

الـ Singleton services مشتركة بين كل الـ requests = threads متعددة. أي mutable field فيها (مثل List<T> أو Dictionary عادي أو متغير counter) لازم يتحمى، وإلا هيحصل race conditions. فضّل الـ Singletons stateless أو immutable أو thread-safe.

07

Synchronization: Locks و Mutexes و Semaphores

Synchronization primitives
Deep dive

الـ synchronization هي أدوات بتنسّق وصول الـ threads للبيانات المشتركة. كل أداة بتحل مشكلة مختلفة وبتكلّف أداء مختلف.

الأداةبتعمل إيهالنطاقasync-friendly؟استخدمها لـ
lock / Monitor / LockMutual exclusion: thread واحد في الـ critical sectionداخل processلا (متعملش await جواه)حماية state قصير في الذاكرة
Interlockedعمليات atomic على متغير واحدداخل processنعم (مفيش blocking)counters، flags، lock-free
MutexMutual exclusion على مستوى الـ OSبين processesلاتأكد إن instance واحدة من التطبيق شغالة
SemaphoreSlimعدّاد: يسمح لـ N threads معاًداخل processنعم (WaitAsync)throttling: max 5 نداءات متزامنة لخدمة
ReaderWriterLockSlimقراء كتير أو كاتب واحدداخل processلاread-heavy shared data
lock (mutual exclusion) T1 inside T2 waits T3 waits SemaphoreSlim(3) T1 T2 T3 T4 waits critical section: [ counter++ ; log.Add(...) ] max 3 concurrent calls to the external API
Lock: thread واحد داخل الـ critical section، والباقي بيستنى. Semaphore(3): تلات threads مسموح لهم معاً
C#Synchronization.cs — lock, SemaphoreSlim (async), Mutex, ReaderWriterLockSlim
// ---- lock: protect an invariant that spans two fields ----
public sealed class BankAccount
{
    private readonly Lock _lock = new();       // private dedicated lock object (.NET 9+). Before: private readonly object _lock = new();
    private decimal _balance;
    private readonly List<string> _log = [];

    public void Deposit(decimal amount)
    {
        lock (_lock)                            // Monitor.Enter / Exit under the hood, released even on exceptions
        {
            _balance += amount;
            _log.Add($"deposit {amount}");      // both updates happen atomically w.r.t. other lock users
        }
    }

    public bool TryWithdraw(decimal amount)
    {
        lock (_lock)
        {
            if (_balance < amount) return false;   // check-then-act is now safe
            _balance -= amount;
            _log.Add($"withdraw {amount}");
            return true;
        }
    }
}

// ---- SemaphoreSlim: limit concurrency of ASYNC work (lock can't span an await) ----
public sealed class RateLimitedClient(HttpClient http)
{
    private readonly SemaphoreSlim _gate = new(initialCount: 3);   // max 3 concurrent requests

    public async Task<string> GetAsync(string url, CancellationToken ct)
    {
        await _gate.WaitAsync(ct);              // takes a slot or waits asynchronously (no thread blocked)
        try   { return await http.GetStringAsync(url, ct); }
        finally { _gate.Release(); }            // ALWAYS release in finally
    }
}

// ---- Mutex (named): only ONE instance of the app per machine ----
using var mutex = new Mutex(initiallyOwned: true, name: "Global\\MyApp.SingleInstance", out bool createdNew);
if (!createdNew) { Console.WriteLine("Already running."); return; }

// ---- ReaderWriterLockSlim: many readers OR one writer ----
var rw = new ReaderWriterLockSlim();
rw.EnterReadLock();  try { /* read shared data */ }  finally { rw.ExitReadLock(); }
rw.EnterWriteLock(); try { /* modify shared data */ } finally { rw.ExitWriteLock(); }

شرح السطور المهمة

  1. lock (_lock) بيضمن إن الـ block مش بيتنفذ إلا من thread واحد في نفس الوقت. بنستخدم lock object خاص (private) مش this ولا typeof(X) ولا string، لأن كود برا ممكن يقفل على نفس الـ object ويعمل deadlock.
  2. في TryWithdraw فحص الرصيد والخصم جوه نفس الـ lock: لو مش كده thread تاني ممكن يسحب بينهم ⇒ رصيد سالب (race من نوع check-then-act).
  3. الـ lock مينفعش يحتوي await (الـ compiler بيمنعه)، لأن ممكن يكمل على thread تاني. للـ async استخدم SemaphoreSlim.WaitAsync.
  4. الـ try/finally مع Release إجباري: لو حصل exception من غير release الـ slot بيضيع للأبد ⇒ الـ semaphore بيقفل تدريجياً.
  5. Mutex مسمّى بيشتغل بين processes (الـ OS هو اللي بيديره) وبالتالي أبطأ من lock. حرف Global\\ في Windows بيخليه على مستوى الجهاز.
  6. الـ ReaderWriterLockSlim بيفيد لما القراءات أكتر بكتير من الكتابات وكل قراءة غالية نسبياً؛ للـ critical sections القصيرة الـ lock العادي غالباً أسرع وأبسط.
قاعدة ذهبية

خلي الـ critical section أقصر ما يمكن: بلاش I/O أو network أو حاجة بطيئة جواها (كل threads التانية واقفة). وبلاش تنادي كود غير معروف (callbacks/events) وانت ماسك lock (هيتعمل deadlock بسهولة).

08

Deadlocks

Deadlocks
Pitfalls

الـ Deadlock هو إن threads (أو أكتر) كل واحد ماسك مورد ومنتظر مورد ماسكه التاني، فمحدش يكمل أبداً. مفيش exception ولا crash، الـ request بس بتفضل معلقة.

Thread 1 Thread 2 Lock A Lock B holds wants B holds wants A ⟳ circular waitnobody can proceed
Circular wait: T1 ماسك A وعايز B، T2 ماسك B وعايز A. الدايرة دي هي الـ deadlock

الـ deadlock بيحصل لما أربع شروط (Coffman) تتحقق مع بعض: (1) Mutual exclusion: المورد مش مشترك. (2) Hold and wait: ماسك مورد وبيطلب تاني. (3) No preemption: مينفعش تاخد المورد بالقوة. (4) Circular wait: دايرة انتظار. كسر أي واحد منهم بيمنع الـ deadlock.

C#Deadlock.cs — the bug, and two fixes
var a = new object();
var b = new object();

// ❌ DEADLOCK: opposite lock order
var t1 = Task.Run(() => { lock (a) { Thread.Sleep(100); lock (b) { Console.WriteLine("t1 done"); } } });
var t2 = Task.Run(() => { lock (b) { Thread.Sleep(100); lock (a) { Console.WriteLine("t2 done"); } } });

try { await Task.WhenAll(t1, t2).WaitAsync(TimeSpan.FromSeconds(2)); }
catch (TimeoutException) { Console.WriteLine("Deadlock detected (timeout)"); }

// ✅ FIX 1: always acquire locks in the SAME global order (breaks circular wait)
var f1 = Task.Run(() => { lock (a) { lock (b) { Console.WriteLine("f1 done"); } } });
var f2 = Task.Run(() => { lock (a) { lock (b) { Console.WriteLine("f2 done"); } } });
await Task.WhenAll(f1, f2);

// ✅ FIX 2: try with a timeout and back off (breaks hold-and-wait)
static bool TryBoth(object x, object y, TimeSpan timeout)
{
    if (!Monitor.TryEnter(x, timeout)) return false;
    try
    {
        if (!Monitor.TryEnter(y, timeout)) return false;
        try { /* critical work with both */ return true; }
        finally { Monitor.Exit(y); }
    }
    finally { Monitor.Exit(x); }
}

التتبع

t1 بياخد a، t2 بياخد b (بعد Sleep الاتنين اتأكدوا إنهم أخدوا أول lock).
t1 بيحاول ياخد b ⇒ مشغول ⇒ بيستنى. t2 بيحاول ياخد a ⇒ مشغول ⇒ بيستنى.
الاتنين منتظرين للأبد. WaitAsync(2s) بيرمي TimeoutException عشان نكتشف المشكلة (من غيره البرنامج هيتعلق).
الحل 1: لو الاتنين بياخدوا a أولاً، اللي ياخدها بيكمل والتاني يستنى في أول lock وهو ماسكش حاجة ⇒ مفيش دايرة.
الـ Deadlock الأشهر في ‎.NET: Sync-over-Async

استدعاء .Result أو .Wait() أو .GetAwaiter().GetResult() على Task غير مكتمل بيحجز thread منتظر. في تطبيقات فيها SynchronizationContext (WinForms/WPF/ASP.NET القديم) ده بيعمل deadlock كلاسيكي لأن الـ continuation محتاجة نفس الـ thread المحجوز. ASP.NET Core ملوش SynchronizationContext فمفيش deadlock حقيقي هناك، لكن بيحصل Thread Pool Starvation (القسم الجاي). القاعدة: async all the way.

إزاي تكتشف deadlock في الـ production؟

  1. الـ request بتعلق من غير errors و CPU قليل ⇒ علامة.
  2. خد dump: dotnet-dump collect -p <pid> ثم dotnet-dump analyze وأمر clrstack -all (أو syncblk) بيوريك كل thread مستني مين.
  3. أو dotnet-stack report -p <pid> للـ stacks بدون إيقاف العملية.
09

Thread Pools و Asynchronous I/O

Thread pools · async I/O · I/O
Deep dive

إنشاء thread جديد غالي (ذاكرة stack + وقت)، فبدل ما نخلق ونقتل threads لكل شغلة، بنحتفظ بـ pool من threads جاهزة بتاخد شغل من queue. الـ ThreadPool في ‎.NET هو اللي بيشغّل Task.Run و async continuations ومعالجة requests في Kestrel.

I/O: Blocking vs Asynchronous

Blocking I/O

الـ thread بينادي read() وبيتحجز (حالة Waiting) لحد ما الداتا توصل. لو 1000 request كل واحد بيستنى DB، محتاج 1000 thread محجوزة وبتاكل ذاكرة وبتعمل context switches.

Asynchronous I/O

الـ thread بيبدأ العملية ويتحرر فوراً. الـ OS بيراقب الإنجاز (IOCP على Windows، epoll على Linux) ولما تخلص بيشغّل الـ continuation على أي thread من الـ pool. مفيش thread مخصص أثناء الانتظار.

sync (blocking) workthread BLOCKED waiting for the database (wasted)work async (await) work no thread used — OS watches the socket (epoll / IOCP) resume → في الـ async الـ thread اتحرر وخدم requests تانية خلال الانتظار thread A: start I/O ➜ serve other requests ➜ … thread B (any): run the continuation
await: الـ thread بيتحرر أثناء الانتظار. الـ OS بيبلّغ لما الـ I/O يخلص فيكمل الكود على thread من الـ pool

Thread Pool Starvation

الـ pool بيبدأ بعدد threads = عدد الـ cores (الحد الأدنى) وبيزوّد threads جديدة ببطء (حوالي واحد كل 500ms تقريباً) لما كل اللي عنده محجوز. لو threads كتير اتحجزت بـ blocking calls (.Result, Thread.Sleep, sync DB calls) والـ requests بتزيد، الـ queue بيطول ⇒ latency بتنفجر رغم إن الـ CPU قليل. ده thread pool starvation.

C#Starvation.cs — blocking vs async endpoints
// ❌ Blocks a pool thread for 2 seconds per request. With 8 cores and 200 concurrent users, the pool starves.
app.MapGet("/bad", () =>
{
    Thread.Sleep(2000);                                    // simulates sync I/O (e.g. .Result on HttpClient)
    return "done";
});

// ❌ Also blocks: "sync over async"
app.MapGet("/bad2", (IHttpClientFactory f) =>
    f.CreateClient().GetStringAsync("https://slow.example.com").Result);

// ✅ Frees the thread while waiting
app.MapGet("/good", async () =>
{
    await Task.Delay(2000);                                // simulates async I/O
    return "done";
});

app.MapGet("/good2", async (IHttpClientFactory f, CancellationToken ct) =>
    await f.CreateClient().GetStringAsync("https://slow.example.com", ct));

// Diagnostics: how loaded is the pool right now?
app.MapGet("/pool", () => new
{
    threads = ThreadPool.ThreadCount,
    queued  = ThreadPool.PendingWorkItemCount,
    completed = ThreadPool.CompletedWorkItemCount
});
  1. /bad بيحجز thread 2 ثانية. مع 200 طلب متزامن محتاج 200 thread لكن الـ pool عنده ~8 وبيزيد ببطء ⇒ طوابير و latency بالثواني، رغم إن الـ CPU شبه فاضي.
  2. /good بيتحرر الـ thread أثناء await فنفس الـ 8 threads بتخدم آلاف الـ requests لأن أغلب وقتها انتظار.
  3. ThreadPool.PendingWorkItemCount مؤشر مبكر: لو كبير ومستمر فالـ pool مشبّع. أدوات: dotnet-counters monitor بيعرض threadpool-queue-length و threadpool-thread-count.
  4. حل سريع مؤقت ThreadPool.SetMinThreads (بيخلي الـ pool يزود بسرعة)، لكن ده تخفيف مش علاج. العلاج: شيل الـ blocking.
async مش threads جديدة

async/await مبيخلقش threads. هو state machine بيقسّم الـ method لأجزاء وبيشغّل الجزء التالي لما الـ I/O يخلص. وللـ CPU-bound محتاج threads فعلاً (Task.Run/Parallel) — لكن متستخدمش Task.Run داخل ASP.NET Core request لتجميل الـ blocking؛ ده بينقل المشكلة لـ thread تاني من نفس الـ pool.

File Systems و I/O

الـ file system بينظّم البيانات على الـ disk في ملفات ومجلدات. على Linux (ext4/xfs): الملف له inode (بيحتفظ بالـ metadata: الحجم، الصلاحيات، مكان الـ blocks) والاسم مجرد entry في directory بتشاور على الـ inode. الـ journaling بيحمي الـ consistency بعد crash. وpage cache بيخزن الملفات المقروءة في الـ RAM، فـ القراءة التانية أسرع بكتير. الكتابة بتروح للـ cache أولاً (write-back) وبعدين للـ disk؛ fsync هو اللي بيجبر الكتابة الفعلية على الـ disk.

C#FileIo.cs — streaming, async I/O, durability
// ❌ Loads the whole file into memory: a 2 GB log = 2 GB of RAM (and LOH allocations)
var all = await File.ReadAllLinesAsync("huge.log");

// ✅ Stream line by line: constant memory
await foreach (var line in ReadLinesAsync("huge.log"))
    if (line.Contains("ERROR")) Console.WriteLine(line);

static async IAsyncEnumerable<string> ReadLinesAsync(string path)
{
    // useAsync: true => real async I/O instead of blocking a thread
    await using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
                                        bufferSize: 64 * 1024, useAsync: true);
    using var reader = new StreamReader(fs);
    while (await reader.ReadLineAsync() is { } line) yield return line;
}

// Durability: WriteAllText returns when data is in the OS cache, NOT necessarily on disk.
await using (var fs = new FileStream("important.dat", FileMode.Create, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough))
{
    await fs.WriteAsync("critical"u8.ToArray());
    await fs.FlushAsync();
    fs.Flush(flushToDisk: true);        // fsync: survive a power loss
}
  1. تحميل ملف كبير بالكامل بيستهلك ذاكرة بحجمه (وعلى الـ Large Object Heap لو أكبر من 85KB). الـ streaming بيحافظ على استهلاك ثابت.
  2. useAsync: true بيطلب async I/O حقيقي من الـ OS بدل ما يحجز thread.
  3. الـ Flush(true) (fsync) بيضمن إن الداتا فعلاً على الـ disk. بدونه ممكن تضيع في حالة انقطاع الكهرباء. غالي، فاستخدمه بس للداتا الحرجة (الـ databases بتعمل كده في الـ WAL).
10

Resource Management

Resource management
Practical

الـ OS بيدّي كل process موارد محدودة: file descriptors/handles، sockets، ذاكرة، CPU، threads. تسريب أي مورد (مش بيتحرر) بيسبب أعطال بعد ساعات أو أيام من التشغيل: Too many open files، OutOfMemory، أو hang.

C#Resources.cs — release deterministically with using
// ❌ Leak: if an exception happens before Close(), the file handle stays open until the GC finalizer (non-deterministic)
var fs = new FileStream("a.txt", FileMode.Open);
var data = new byte[fs.Length];
fs.Read(data);
fs.Close();

// ✅ using: Dispose() is called even if an exception is thrown
using (var stream = new FileStream("a.txt", FileMode.Open))
{
    var buffer = new byte[stream.Length];
    stream.Read(buffer);
}                                              // handle released here

// C# 8+: using declaration — disposed at the end of the enclosing scope
using var conn = new Microsoft.Data.SqlClient.SqlConnection("...");
await using var tx = await conn.BeginTransactionAsync();   // IAsyncDisposable

// Your own resource: implement IDisposable correctly
public sealed class TempFile : IDisposable
{
    public string Path { get; } = System.IO.Path.GetTempFileName();
    public void Dispose() { if (File.Exists(Path)) File.Delete(Path); }
}
  1. الـ GC بيدير الذاكرة بس، مش الـ handles والـ sockets والـ connections. دي unmanaged resources لازم تتحرر بـ Dispose.
  2. الـ using بيتحول لـ try/finally بيستدعي Dispose. الـ using declaration أنضف (من غير nesting).
  3. حدود الـ OS: على Linux ulimit -n بيحدد أقصى file descriptors لكل process (غالباً 1024 كـ soft default). الـ sockets كمان بتتحسب منها. تسريب connections ⇒ Too many open files.
  4. مؤشرات التسريب: استهلاك يزيد مع الوقت (dotnet-counters)، lsof -p <pid> | wc -l بيعد الـ handles المفتوحة، وعدد threads بيكبر.
حدود الـ Containers

في Docker/Kubernetes بتحدد memory limit و CPU limit. تخطي الذاكرة = OOMKilled (الـ kernel بيقتل الـ process مباشرة بدون exception). الـ CPU limit بيعمل throttling (الـ app بتبطأ مش بتقع). و Environment.ProcessorCount في ‎.NET بتعكس الـ CPU limit، وده بيأثر على حجم الـ thread pool والـ parallelism.

11

Linux Basics و CLI و Permissions و Bash

Linux basics · CLI tools · permissions · bash scripting
Practical

أغلب الـ production للـ ‎.NET دلوقتي على Linux (containers). لازم تتعامل بثقة مع الـ shell. مبدأ يونكس: كل حاجة ملف (devices، sockets، processes في /proc)، وأدوات صغيرة بتتركّب مع بعض بـ pipes (|).

PathPurpose
/root of the file system
/etcconfiguration files
/var/loglogs (/var/log/syslog, nginx logs…)
/home/<user> · /tmpuser files · temporary files
/proc · /sysvirtual FS exposing kernel/process info (/proc/<pid>/status)
/usr/bin · /optbinaries · optional apps (/opt/myapp)

أدوات الـ CLI الأساسية

BashEveryday Linux CLI for a backend engineer
# --- navigate & inspect ---
pwd; ls -lah /var/log; cd /opt/myapp
tail -n 100 -f app.log                # follow a log live (Ctrl+C to stop)
less +G app.log                       # page through, jump to end

# --- grep: find lines (-r recursive, -n line numbers, -i ignore case, -C 3 context) ---
grep -rn "NullReferenceException" /var/log/myapp/
grep -i -C 3 "timeout" app.log

# --- awk: columns.  Top 10 client IPs in an nginx access log ---
awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -10

# --- sed: stream editor. Replace text; print a line range ---
sed -i 's/Server=localhost/Server=db.internal/g' appsettings.Production.json
sed -n '120,140p' app.log

# --- processes ---
ps aux | grep dotnet                  # who's running, PID, CPU%, MEM%
top                                   # live view (htop is nicer). Press M = sort by memory, P = CPU
kill -15 4120                         # SIGTERM: ask nicely (graceful shutdown)
kill -9  4120                         # SIGKILL: forced (no cleanup!)

# --- systemd services & logs ---
systemctl status myapp
sudo systemctl restart myapp
journalctl -u myapp --since "10 min ago" -f      # service logs, follow
journalctl -u myapp -p err -n 50                 # last 50 error-level lines

# --- disk / memory / network ---
df -h; du -sh /var/log/*; free -m
ss -tlnp                                          # listening ports + owning process
  1. الـ pipe | بيوصّل stdout بتاع أمر بـ stdin بتاع التاني. المثال بتاع awk: استخرج العمود الأول (IP) ⇒ sort يجمّع المتشابه ⇒ uniq -c يعد ⇒ sort -rn ترتيب تنازلي ⇒ head أعلى 10. ده pipeline كامل بدون برنامج.
  2. SIGTERM (15) بتسمح للتطبيق ينظف ويقفل بهدوء (graceful shutdown)، أما SIGKILL (9) بيقتل فوراً ومش ممكن التطبيق يمسكها. ابدأ دايماً بـ 15.
  3. journalctl -u بيقرا logs الـ service اللي تحت systemd (stdout/stderr للتطبيق بتروح هناك).

Permissions والمستخدمين

كل ملف له owner وgroup وثلاث مجموعات صلاحيات: للـ owner (u)، للـ group (g)، للباقي (o). كل مجموعة: r=4 (قراءة)، w=2 (كتابة)، x=1 (تنفيذ، أو دخول للمجلد).

-rwxr-xr-- 1 deploy app 8192 Nov 11 run.sh owner (deploy)rwx4+2+1 = 7 group (app)r-x4+0+1 = 5 othersr--4+0+0 = 4
قراءة صلاحيات الملف: rwxr-xr-- = owner: rwx (7) · group: r-x (5) · others: r-- (4) ⇒ 754
BashPermissions and users
ls -l run.sh                          # -rw-r--r-- 1 deploy app 120 run.sh
chmod 755 run.sh                      # owner rwx, group r-x, others r-x  (scripts / executables)
chmod 644 notes.txt                   # owner rw-, others r--             (normal files)
chmod 600 id_rsa                      # private keys: owner only (ssh refuses looser perms)
chmod +x run.sh                       # just add execute
chown deploy:app /opt/myapp -R        # change owner:group recursively

id                                    # who am I? uid, gid, groups
sudo -u appuser dotnet MyApp.dll      # run as another user
# NEVER run your web app as root: a bug (RCE) becomes full control of the machine.

Bash Scripting Basics

Bashdeploy.sh — a safe, readable script
#!/usr/bin/env bash
set -euo pipefail          # -e stop on error, -u error on unset variable, -o pipefail fail if any pipe stage fails

APP_DIR="/opt/myapp"
BACKUP_DIR="/var/backups/myapp"
VERSION="${1:?Usage: deploy.sh <version>}"      # required argument

log() { echo "[$(date +%H:%M:%S)] $*"; }

log "Backing up current release"
mkdir -p "$BACKUP_DIR"
tar -czf "$BACKUP_DIR/myapp-$(date +%F).tgz" -C "$APP_DIR" .

log "Deploying $VERSION"
if curl -fsS -o /tmp/app.zip "https://artifacts.internal/myapp/$VERSION.zip"; then
    unzip -oq /tmp/app.zip -d "$APP_DIR"
else
    log "Download failed"; exit 1
fi

sudo systemctl restart myapp
for i in {1..10}; do
    if curl -fs http://localhost:8080/health >/dev/null; then log "Healthy"; exit 0; fi
    sleep 2
done
log "Health check failed"; exit 1
  1. set -euo pipefail هو أهم سطر: من غيره السكريبت بيكمل بعد أخطاء ويعمل أضرار صامتة.
  2. "${1:?...}" بيطلب المعامل الأول وإلا بيطبع رسالة ويقف. دايماً حط المتغيرات بين " " لتجنب مشاكل المسافات.
  3. curl -fsS: -f بيفشل على HTTP errors، -s هادي، -S يعرض الخطأ. الـ exit code هو اللي بيحدد النجاح (0) أو الفشل (غير صفر) وبيتعمل عليه if.
  4. السكريبت بيعمل backup → deploy → restart → health check، وبيرجّع كود فشل لو الـ health check فشل (عشان الـ CI يعرف).
12

Processes والـ Environment Variables جوه Containers و cgroups و namespaces

Container internals: processes, env vars, cgroups, namespaces
Deep dive

الـ container مش VM. هو process عادية على الـ host بس الـ kernel بيخدعها وبيحدد مواردها باستخدام ميزتين: namespaces (بتحدد «إيه اللي تشوفه») وcgroups (بتحدد «كام تستخدم»). Docker بيبني فوقهم.

Host (one Linux kernel shared by all containers) Container A (your API) PID namespace: sees its own PIDs (app = PID 1)NET namespace: own IP, ports, interfacesMNT namespace: own root filesystemUTS / IPC / USER namespaces cgroup: memory ≤ 512MBcpu ≤ 1.0 core · pids ≤ 200 Container B (SQL / Redis …) same kernel, different namespacesisolated from A (can't see A's processes) cgroup: memory ≤ 1GBcpu ≤ 2.0 cores
الـ container = process + namespaces (عزل الرؤية) + cgroups (حدود الموارد) + filesystem layers

Namespaces

pid (الـ process يشوف نفسه PID 1)، net (شبكة خاصة)، mnt (file system خاص)، uts (hostname)، ipc، user (mapping للمستخدمين). العزل ده «رؤية» مش أمان مطلق (kernel مشترك).

cgroups (control groups)

بتحدد وتراقب استهلاك المجموعة: ذاكرة، CPU، I/O، عدد الـ processes. تخطي الذاكرة ⇒ OOM kill. تخطي CPU ⇒ throttling (تبطيء).

BashSee it with your own eyes
# Limits are cgroup settings, nothing more
docker run -d --name api --memory=512m --cpus=1.5 -e ASPNETCORE_ENVIRONMENT=Production \
           -e ConnectionStrings__Default="Host=db;Database=shop" -p 8080:8080 myorg/shop-api:1.0

docker exec api cat /sys/fs/cgroup/memory.max          # 536870912   (cgroup v2: 512MB in bytes)
docker exec api cat /sys/fs/cgroup/cpu.max             # 150000 100000  (1.5 cores)
docker exec api ps aux                                  # the app is PID 1 inside the container
docker exec api printenv | grep -E 'ASPNETCORE|Connection'

# Same process, seen from the HOST (different PID, same kernel)
ps aux | grep MyApp.dll

# Namespaces in action: start a shell in new PID + mount namespaces without Docker
sudo unshare --pid --fork --mount-proc bash -c 'ps aux'   # shows only 2 processes
  1. --memory و --cpus بيتترجموا لملفات cgroup (memory.max, cpu.max). الـ container مش بيعمل «حجز» لـ RAM، دي مجرد حدود.
  2. -e بيحقن environment variables في process الـ container. في ASP.NET Core الـ config provider للـ environment بيحوّل الـ __ (underscore مزدوج) لـ : فـ ConnectionStrings__Default = ConnectionStrings:Default. بيتفوّق على appsettings.json، فهو الطريقة القياسية للـ secrets/config في الـ containers (من أسرار الـ orchestrator مش من الـ image).
  3. التطبيق هو PID 1 جوه الـ container: يعني هو اللي بيستقبل SIGTERM لما docker stop يحصل. لو مبيتعاملش معاه الـ container بتتقتل بعد 10 ثواني (SIGKILL). الـ ‎.NET Generic Host بيلتقط SIGTERM ويعمل graceful shutdown (HostOptions.ShutdownTimeout الافتراضي 30 ثانية في النسخ الحديثة، فظبطه أقل من grace period بتاع الـ orchestrator).
  4. PID 1 مسؤول كمان عن تنظيف الـ zombie processes؛ لو بتشغّل child processes استخدم --init في Docker.
  5. الـ unshare بيثبت إن الـ container مجرد process في namespaces جديدة: مفيش «ماكينة» ثانية.
مشاكل شائعة

(1) الـ app بتتقتل من غير exception ⇒ OOMKilled (docker inspect ⇒ OOMKilled: true). ارفع الـ limit أو قلل الاستهلاك. (2) بطء مع CPU limit صغير ⇒ throttling؛ شوف cpu.stat. (3) الـ app مبتقفلش بهدوء ⇒ مش بتستقبل SIGTERM (الـ shell form في CMD بيحط shell قبلها)، استخدم exec form: ENTRYPOINT ["dotnet","MyApp.dll"]. (4) secrets اتكتبت جوه الـ image أو في env variables بتتسرّب في الـ logs.

13

أخطاء شائعة وتشخيص

Common mistakes and troubleshooting
Pitfalls
العَرَضالسببالتشخيص / الحل
Latency عالية والـ CPU قليلThread pool starvation من blocking callsdotnet-counters: threadpool-queue-length. شيل .Result/.Wait()، استخدم async
أرقام عشوائية / داتا مفقودة تحت loadRace condition على shared stateحدد الـ mutable shared state (غالباً في Singleton). Interlocked / lock / Concurrent* / immutable
Requests معلقة من غير errorDeadlockdotnet-dump + clrstack -all. ثبّت ترتيب الـ locks، ومتستخدمش lock حول await
الـ app بتقع في Docker من غير logOOMKilleddocker inspect، راقب الـ working set، ارفع الـ limit أو قلل الـ allocations
Too many open filesتسريب file handles / sockets أو limit صغيرlsof -p، using / IHttpClientFactory، رفع ulimit -n
StackOverflowExceptionrecursion بلا حد أو عميقةحوّلها لـ iterative بـ Stack<T>. مش ممكن تمسكها بـ catch
Memory بتزيد باستمرارLeak (objects عالقة في static/event handler/cache بلا حد)dotnet-gcdump / dotnet-dump وقارن الـ heap بين لقطتين
Permission deniedصلاحيات ملف/مستخدم غلطls -l، id، chown/chmod مع أقل صلاحية ممكنة
14

Knowledge Check

Takeaways · conceptual questions · code reading · interview questions
Basics

أهم النقاط

  • Process = ذاكرة معزولة. Thread = خط تنفيذ بيشارك الـ heap مع باقي threads الـ process وده مصدر الـ race conditions.
  • الـ context switch والـ syscalls ليهم تكلفة؛ threads أكتر من الـ cores مش بتسرّع الشغل الـ CPU-bound، والـ batching بيقلل الـ syscalls.
  • Stack سريع ومحدود وخاص بالـ thread، Heap مشترك ومدار بالـ GC. Virtual memory بتديك عزل و demand paging؛ الـ page faults من الـ disk غالية.
  • Race condition = بيانات مشتركة + مفيش synchronization. الحل: عدم المشاركة أو Interlocked أو lock أو immutability.
  • Deadlock يحتاج circular wait. كسره بترتيب ثابت للـ locks أو timeouts. وفي async: async all the way.
  • Async I/O بيحرر الـ threads أثناء الانتظار. Blocking في ASP.NET Core ⇒ thread pool starvation.
  • Container = process + namespaces + cgroups. الـ limits بتأثر على الـ GC والـ thread pool، والتخطي ⇒ OOMKilled.

أسئلة مفاهيمية

ليه lock مينفعش يتحط حوالين await؟

الـ lock مربوط بالـ thread اللي مسكه، والـ await ممكن يكمل على thread تاني فمستحيل يعمل release صح، لذلك الـ compiler بيمنعه. للـ async استخدم SemaphoreSlim(1,1) مع WaitAsync.

فرّق بين Mutex و SemaphoreSlim و lock.

lock: thread واحد، داخل process، سريع. Mutex: thread واحد لكن على مستوى OS فبيشتغل بين processes (أبطأ). SemaphoreSlim(N): N threads، وبيدعم async.

إيه الفرق بين الـ virtual size والـ working set؟ وأيهم بيتحاسب عليه الـ container؟

الـ virtual size هو الـ address space المحجوز، والـ working set هو اللي في الـ RAM فعلاً. الـ cgroup بيحاسب على الذاكرة الفعلية المستهلكة (RSS + page cache تبع الـ container)، مش الـ virtual.

ليه Environment.ProcessorCount مهم في container؟

لأنه بيحدد حجم الـ thread pool الابتدائي ودرجة الـ parallelism. في ‎.NET بيعكس CPU limit الخاص بالـ container (مش cores الـ host)، فلو limit = 1 core، الـ pool ابتدائيته صغيرة و blocking calls هتخنقه بسرعة.

الـ Heisenbug معناه إيه؟ ومثال؟

bug بيختفي أو بيتغير لما تحاول تراقبه (debugger/log بيغيّر التوقيت). مثال كلاسيكي: race condition، أو memory corruption.

قراءة كود

C#Find the bugs
public class Cache
{
    private readonly Dictionary<string, string> _items = new();

    public string GetOrAdd(string key, Func<string> factory)
    {
        if (!_items.ContainsKey(key))
            _items[key] = factory();
        return _items[key];
    }
}

// Registered as Singleton and used from many requests concurrently
إيه المشاكل؟ وإزاي تصلحها؟

(1) Dictionary غير thread-safe: كتابة متزامنة ممكن تفسد البنية الداخلية (exception، infinite loop، أو بيانات مفقودة). (2) check-then-act: threads اتنين ممكن يعدّوا ContainsKey مع بعض فيشغّلوا factory() مرتين. الحل: ConcurrentDictionary.GetOrAdd(key, k => factory()) (لاحظ إن الـ factory ممكن تتنفذ أكتر من مرة، فاستخدم Lazy<T> كـ value لو لازم مرة واحدة) أو lock حول العملية كلها.

C#Why is this endpoint slow under load?
app.MapGet("/report", (ReportService svc) =>
{
    var data = svc.LoadAsync().Result;      // returns Task<Report>
    return Results.Ok(data);
});
التشخيص والحل؟

.Result بيحجز thread من الـ pool طول فترة الـ I/O ⇒ مع load عالي الـ pool يتشبع (starvation) و latency تنفجر رغم CPU فاضي. الحل: async (ReportService svc) => Results.Ok(await svc.LoadAsync()) وتمرير CancellationToken.

أسئلة إنترفيو شائعة

اشرح الفرق بين process و thread و task في ‎.NET.

Process: ذاكرة معزولة. Thread: كيان تنفيذ في الـ OS. Task: تجريد لعملية (ممكن CPU أو I/O) بتتجدول غالباً على thread من الـ ThreadPool، وممكن يكون مفيش thread خالص أثناء انتظار الـ I/O.

امتى تستخدم Parallel.ForEach وامتى async/await؟

Parallel للـ CPU-bound المقسّم على cores. async/await للـ I/O-bound (DB، HTTP، ملفات) لتحرير الـ threads. الخلط الشائع: Parallel.ForEach بداخله I/O blocking، أو Task.Run لتغليف I/O.

الـ container أمني زي الـ VM؟

لأ. الـ VM عنده kernel مستقل (عزل أقوى عن طريق hypervisor). الـ container بيشارك الـ kernel مع الـ host، فثغرة kernel أو container escape أخطر؛ عشان كده بنزود: non-root user، read-only filesystem، seccomp/AppArmor، وإسقاط الـ capabilities.

لو الـ app بتبطأ بعد ساعات من التشغيل، تدور على إيه؟

تسريب موارد (memory/handles/threads/connections)، تراكم في cache بلا حد، عدد threads بيزيد، GC pauses بسبب heap كبير، أو starvation تدريجي. أبدأ بـ dotnet-counters (GC، thread pool، exceptions) ثم dump/gcdump للمقارنة.

↗

المراجع والقراءة الإضافية

References & further reading

الدرس بيشرح الفكرة نفسها؛ الروابط دي للتحقق والتعمق والرجوع لتفاصيل الـ API. (محتاجة إنترنت.)

مصادر تعليمية ومتقدمة — Third-party & advanced reading

خريطة التغطية: 24 عنصر من الـ Roadmap ومكان شرحه في الدرس
RoadmapProcesses vs Threads§01
RoadmapProcess and Thread Lifecycle§01
RoadmapScheduling Concepts§02
RoadmapContext Switching§02
RoadmapUser Mode vs Kernel Mode§03
RoadmapStack and Heap§04
RoadmapVirtual Memory and Paging Concepts§04
RoadmapSynchronization§07
RoadmapLocks, Mutexes, and Semaphores§07
RoadmapRace Conditions§06
RoadmapDeadlocks§08
RoadmapConcurrency vs Parallelism§05
RoadmapFile Systems§11
RoadmapI/O§09
RoadmapSystem Calls Concepts§03
RoadmapResource Management§10
RoadmapAsynchronous I/O§09
RoadmapThread Pools§09
RoadmapLinux Basics§11
SuggestedLinux CLI: grep, awk, sed, ps, top, journalctl§11
SuggestedFile permissions and users§11
SuggestedBash scripting basics§11
SuggestedProcesses and environment variables inside containers§12
Suggestedcgroups and namespaces (what Docker is built on)§12

خلصت الدرس وحليت الأسئلة؟ علّم عليه عشان يتحسب في تقدّمك.

محتويات الدرس