Interview Handbook by Sayed Elmahdy English

المحور 25 · أساسيات بتفرّق معاك

أساسيات الـ Operating System

Process و Thread، و Context switch، و Memory و Virtual memory، و I/O، و Scheduling.

اختياري بس بيفرق: مش هيتسأل فيه في كل انترفيو، بس معرفته بتعمّق فهمك وبتميّزك عن غيرك.

16 سؤالJunior · 4Mid · 7Senior · 510 اختيارات

المفاهيم

هنفهم إيه؟ هنربط مفاهيم نظام التشغيل بمشاكل اللي بتظهر وقت الضغط: بطء خدمة، استهلاك ذاكرة، انتظار ، أو تشغيلها داخل container. ابدأ بالعلاقة بين process وthread وTask، وبعدها شوف إزاي الذاكرة والتزامن والـ I/O بتأثر على التشغيل.

قبل ما تبدأ: يكفي تعرف إن البرنامج بيتنفذ على جهاز، وإن .NET runtime بيدير كائنات البرنامج. الـ process برنامج شغال ومعاه موارده؛ thread مسار تنفيذ داخله؛ وTask تمثل عملية ونتيجتها، ومش معناها thread جديدة. كل الموضوعات هنا اختيارية للتشخيص، ومش مطلوب حفظ تفاصيل kernel.

المصطلحات اللي تحتها خط منقّط تقدر تضغط عليها لمعرفة معناها، وترجع تكمل من نفس مكانك.

#اختياري: Process و Thread و TaskBonusOptional: processes, threads and tasks

اختياري بس بيفرق: مش هيتسأل فيه في كل انترفيو، بس معرفته بتعمّق فهمك وبتميّزك عن غيرك.

الـ ينفذ التعليمات؛ logical CPU هو مسار تنفيذ ظاهر للـ وقد يكون نواة فعلية أو مسارًا منطقيًا. الـ scheduler يوزع وقت التنفيذ بين threads الجاهزة. كلمة «جاهزة» تعني إنها تقدر تكمل لو اتخصص لها CPU، عكس thread منتظرة أو قفل. هنستخدم الفرق ده لما نفسر async لاحقًا.

الموضوع كله bonus: مفيد لفهم runtime وتشخيص production، لكنه مش شرط تكون حافظ تفاصيل kernel علشان تشتغل .

الـ OS بيحتاج يفصل برامج عن بعض ويوزع وقت الـ CPU. الـ process حاوية موارد وعنوان ذاكرة افتراضي؛ الـ thread مسار تنفيذ جوه process وليه registers و stack. threads في نفس process بتشارك heap وموارد، فمحتاجين synchronization. الـ Task في .NET بتمثل عملية واكتمالها، مش OS thread جديدة.

process شبه مكتب بملفاته، و threads موظفين بيشاركوا الملفات، و Task طلب شغل. الطلب ممكن يستنى رسالة من برّه من غير موظف واقف مستنيه.

ProcessThreadTask
المالكOSOS scheduler.NET abstraction
العزلaddress space مستقلة عادةبيشارك process memoryمفيش عزل ذاكرة خاص
أثناء I/Oيفضل موجودمش لازم thread محجوزة لكل عملية asyncممكن يمثل انتظار من غير thread مخصصة

CPU-bound Tasks غالباً بتشتغل على ThreadPool؛ I/O Tasks بتعتمد على والـ OS. process منفصلة مفيدة للعزل أوتشغيل برنامج خارجي، مش بديل رخيص لكل method call.

#اختياري: شكل ذاكرة ProcessBonusOptional: process memory layout

اختياري بس بيفرق: مش هيتسأل فيه في كل انترفيو، بس معرفته بتعمّق فهمك وبتميّزك عن غيرك.

قبل الخريطة: virtual address عنوان يستخدمه البرنامج، والنظام يربطه بصفحة ذاكرة فعلية أو backing storage عند الحاجة. managed memory يديرها ؛ native memory تخصصها مكتبات أو استدعاءات النظام ولا يجمعها GC ككائن .NET. الـ compiler يحول إلى تعليمات المعالج وقت التشغيل، و يغيّر عناوين الذاكرة بين التشغيلات لأسباب أمنية. الشكل التالي تقريبي للتعلّم.

علشان تفهم memory growth، فرّق بين مناطق العملية بدل اعتبارها heap واحدة. الشكل ده تعليمي؛ ترتيب العناوين الفعلي بيتغير بالـ والـ runtime والـ ASLR.

المنطقةمحتواها
Codeexecutable code؛ JIT ممكن يضيف code pages وقت التشغيل
Datanative globals و runtime data؛ managed static references مش معناها objects في native data section
Heapmanaged objects و native بمناطق يديرها runtime أو allocator
Stack لكل threadcall frames وحالة التنفيذ، مع إمكانية إبقاء قيم في registers
Mapped regionslibraries و memory-mapped files و shared mappings

value type مش معناه stack دائماً: field جوه object بيتخزن inline جواه، و بيعمل managed object، و async state ممكن تعيش في heap. المثال .NET console app مع using System.Diagnostics;، والأرقام لقطة تقريبية مش memory profiler.

using System.Diagnostics;

using var process = Process.GetCurrentProcess();
process.Refresh();
Console.WriteLine($"Resident bytes: {process.WorkingSet64}"); // (1)
Console.WriteLine($"Managed estimate: {GC.GetTotalMemory(false)}"); // (2)
🧾 شرح الكود
  1. (1) working set ذاكرة resident للعملية، وبتشمل أكتر من managed heap وممكن shared pages.
  2. (2) تقدير managed allocated memory من غير طلب GC؛ مش كل process memory ولا reserved address space.

لو managed heap ثابتة و working set بتكبر، فتش على native allocations و stacks و mapped files، مع فهم اختلاف المقاييس بين أنظمة التشغيل.

#اختياري: Scheduling و Context switchingBonusOptional: scheduling and context switching

اختياري بس بيفرق: مش هيتسأل فيه في كل انترفيو، بس معرفته بتعمّق فهمك وبتميّزك عن غيرك.

مثال خطوة بخطوة
  1. افترض نواة معالج واحدة وعمليتين جاهزتين. نظام التشغيل يسمح للأولى بفترة تنفيذ ثم يبدّل للثانية، فتبدو الاثنتان متقدمتين خلال نفس الفترة.
  2. Context switch يحفظ حالة التنفيذ الحالية ويستعيد حالة أخرى؛ التبديل له تكلفة، وقد تتأثر بيانات الكاش. concurrency هنا لا تعني إن النواة نفذت التعليمتين في اللحظة نفسها.
  3. لو المهمة تنتظر ، قد يشغل النظام مهمة جاهزة بدلها. زيادة threads بلا قياس قد تزود التبديل والذاكرة من غير زيادة الشغل المكتمل.

عدد threads الجاهزة غالباً أكبر من logical CPUs. scheduler بيختار مين يشتغل، وممكن يعمل preemption علشان يدي غيره فرصة. time slice و priority policies بتختلف حسب والـ scheduling class؛ مش وعد بوقت ثابت ولا ضمان ترتيب عادل تماماً.

  1. thread تشتغل لحد block أو yield أوقرار preemption.
  2. الـ OS يحفظ execution context زي registers ومكان التنفيذ.
  3. يشغل thread تانية؛ caches و locality ممكن تتأثر. تغيير process ممكن يضيف تكلفة address-space handling.
  4. لما الأولى ترجع، بتكمل من حالتها المحفوظة، مش من أول method.

context switch ليه direct cost وكلفة غير مباشرة من cache misses، بس مفيش رقم ثابت صالح لكل جهاز. زيادة threads مش بالضرورة زيادة ؛ ممكن تزود contention و memory و switching. thread priority العالية ممكن تجوّع غيرها أوتدخل في priority inversion؛ مش علاج لبطء query.

await ممكن يكمل synchronously لو العملية خلصت، ومش معناه OS context switch عند كل await. علشان تشخص مرتفع راقب runnable work و contention و مع ، مش thread count بس.

#اختياري: Mutex و Semaphore و SpinlockBonusOptional: mutexes, semaphores and spinlocks

اختياري بس بيفرق: مش هيتسأل فيه في كل انترفيو، بس معرفته بتعمّق فهمك وبتميّزك عن غيرك.

مشاركة resource محتاجة قواعد دخول، لكن اختيار primitive غلط ممكن يحول كل البرنامج لطابور. يسمح بمالك واحد، و بيسمح بعدد محدد من الداخلين. spinlock بيفضل يلف على بدل النوم، فمناسب فقط لانتظار بالغ القصر بعد قياس، مش حول .

الاختيارالاستخدام والمقابل
mutexملكية thread؛ بعض الأنظمة تدعم named mutex بين processes، مع اختلافات platform
OS semaphoreعداد تصاريح؛ مش نفس ملكية mutex
lock و Lockتنظيم جوه process لـ synchronous critical section قصيرة
SemaphoreSlimتنظيم داخل process، و WaitAsync للكود async؛ مش cross-process semaphore
SpinLockشغل منخفض المستوى؛ دوران يهدر CPU لو صاحب القفل مش قادر يشتغل

fragment داخل class بيحد الشغل المتزامن؛ محتاج Dispose للـ semaphore عند انتهاء عمر الخدمة وبعد انتهاء مستخدميها.

private readonly SemaphoreSlim slots = new(4, 4);

public async Task RunLimitedAsync(Func<Task> work, CancellationToken ct)
{
    await slots.WaitAsync(ct); // (1)
    try
    {
        await work(); // (2)
    }
    finally
    {
        slots.Release(); // (3)
    }
}
🧾 شرح الكود
  1. (1) مستني تصريح من غير thread blocked في الانتظار async.
  2. (2) أربع calls كحد أقصى جوا المنطقة لكل instance من class، مش لكل cluster.
  3. (3) release حتى لو work فشل. لو WaitAsync اتلغت، مش بندخل try ومش بنرجع تصريح ماخدناهوش.
قبل C# 13C# 13 وما بعده
lock على private objectSystem.Threading.Lock خيار مخصص للـ synchronous locking

مفيش await جوه lock؛ استخدم primitive مناسبة للسياق، وماتخلطش mutex مملوكة لـ thread مع continuation ممكن تكمل على thread تانية.

#اختياري: Deadlock و شروط CoffmanBonusOptional: deadlock and the Coffman conditions

اختياري بس بيفرق: مش هيتسأل فيه في كل انترفيو، بس معرفته بتعمّق فهمك وبتميّزك عن غيرك.

بيحصل لما أطراف تستنى موارد ماسكها بعض ومحدش يقدر يتقدم. في النموذج الكلاسيكي، الأربع شروط لازم يجتمعوا؛ وجودهم لوحده مش معناه إن deadlock حصل بالفعل.

الشرطالمعنىطريقة كسره
Mutual exclusionresource مش قابلة للمشاركةمشاركة آمنة أو لو ممكن
Hold and waitماسك مورد ومستني غيرهاحصل على الموارد مع بعض أواتركها قبل الانتظار
No preemptionالمورد مش بيتسحب قهرياً بأمانتصميم release و rollback لما ينفع
Circular waitدائرة انتظار بين الأطرافترتيب ثابت لاكتساب الموارد

لو نقل رصيد بين حسابين محتاج قفلين، رتبهم بـ account ID في كل المسارات. timeout يدي فرصة تفشل أوتعيد المحاولة، لكنه مش بيحل التصميم تلقائياً؛ لازم تفك اللي ماسكه وتتعامل مع partial work. starvation مختلف: شغل مش بياخد فرص كفاية؛ livelock فيه نشاط مستمر من غير تقدم مفيد.

deadlock مش مقصور على thread blocking. Tasks ممكن تنتظر بعض async في دائرة برضه؛ async/await مش ضمان ضد دوائر الاعتماد.

#اختياري: Virtual memory و Paging و Page faultsBonusOptional: virtual memory, paging and page faults

اختياري بس بيفرق: مش هيتسأل فيه في كل انترفيو، بس معرفته بتعمّق فهمك وبتميّزك عن غيرك.

كل process بتشوف address space افتراضية؛ hardware والـ بيترجموا صفحاتها لـ physical frames أو backing storage. الحجز الافتراضي مش معناه فعلية مستخدمة. الـ OS بيستعمل paging للحماية والمشاركة والتحميل عند الحاجة، مش مجرد تعويض نقص RAM.

  1. برنامج يلمس virtual address، و translation تتراجع عبر أو page tables.
  2. لو الصفحة مش حاضرة أوالوصول مخالف للصلاحيات، يحصل page fault ويتدخل الـ OS.
  3. valid demand page ممكن تتجهز بzero-fill أو mapping موجود، من غير disk ؛ minor fault مش خطأ تطبيق بالضرورة.
  4. لو محتاجة قراءة من storage، الانتظار أغلى؛ ده major fault بالمصطلح الشائع على Linux.
  5. invalid access ممكن يتحول لفشل للعملية، بدل تحميل صفحة.

working set أو resident set هو الصفحات الموجودة حالياً في RAM للعملية، بتفاصيل مختلفة حسب OS. resident pages مش كلها unique أو private. ضغط الذاكرة وكثرة paging ممكن يسبب thrashing: وقت أكتر بيتصرف في نقل صفحات بدل شغل مفيد.

تابع process metrics و container metrics مع بعض؛ file cache ممكن تتحسب على cgroup، و swap ممكن تكون مقفولة أومحدودة. زيادة virtual memory مش دليل leak لوحدها، و page fault مش معناها disk read دايماً.

#اختياري: GC علاقتها بالـ OS و Server GCBonusOptional: the GC, the OS and Server GC

اختياري بس بيفرق: مش هيتسأل فيه في كل انترفيو، بس معرفته بتعمّق فهمك وبتميّزك عن غيرك.

الـ بتدير عمر managed objects فوق نظام الذاكرة الافتراضية؛ الـ بيدير mappings والصفحات والموارد على مستوى العملية. لما GC تجمع object مش لازم working set تنزل فوراً؛ runtime ممكن تحتفظ بذاكرة لاستخدام لاحق، والـ OS له قراراته في residency.

Workstation GCServer GC
الهدف العاماحتياجات تطبيقات client أوموارد محدودة لتطبيقات server مع parallel collection
التصميمتنظيم أقل تعقيداً للـ heapsmultiple heaps و dedicated collection threads حسب runtime والموارد والإعدادات
القرارقيس و throughput و memory على limits الفعلية؛ الاسم مش ضمان أفضل أداء

web بيطلب Server GC افتراضياً، لكن افحص الوضع الفعلي بـ GCSettings.IsServerGC. runtime ممكن يتكيف مع والـ memory limits، والتفاصيل بتتطور؛ ماتحفظش «heap ثابت لكل CPU» كقانون مطلق.

managed heap جزء من process footprint؛ native buffers و thread stacks و code كمان موجودين. GC heap hard limit مش cap لكل process memory. سيب headroom للـ native memory والـ OS accounting؛ container ممكن تتقتل قبل ما تشوف OutOfMemoryException managed. Workstation و Server GC.

#اختياري: I/O models و epoll و kqueue و IOCPBonusOptional: I/O models, epoll, kqueue and IOCP

اختياري بس بيفرق: مش هيتسأل فيه في كل انترفيو، بس معرفته بتعمّق فهمك وبتميّزك عن غيرك.

لو كل socket مستنية thread، عدد connections الكبير هيستهلك stacks و scheduler. blocking بيوقف thread لحد نتيجة؛ non-blocking I/O بيرجع بسرعة لو مفيش داتا؛ multiplexing بيسمح بمراقبة sockets كتير من غير thread لكل واحدة.

الآليةالفكرة
epoll على Linuxreadiness notification: socket جاهزة لمحاولة read أو write من غير انتظار
kqueue على أنظمة BSD و macOSevent notification لموارد كتير، منها sockets
على Windowscompletion notification لعمليات I/O مدعومة بدأت بالفعل

socket async بتخفي كتير من الاختلافات. await بتتعامل مع اكتمال العملية؛ مش هي اللي بتنفذ epoll بنفسها. مش كل async API معناها zero blocked threads تحتها: file I/O وسلوك providers والـ ممكن يختلفوا.

المثال fragment في async method، مع using System.Net.Sockets;. socket متصلة بالفعل و ct متاح. ده read واحدة، مش protocol framing كامل.

byte[] buffer = new byte[4096];
int read = await socket.ReceiveAsync(buffer.AsMemory(), SocketFlags.None, ct); // (1)
if (read == 0) // (2)
    return;
Console.WriteLine($"Received {read} bytes"); // (3)
🧾 شرح الكود
  1. (1) العملية ممكن تخلص فوراً أوتكمل لاحقاً من غير thread منتظرة لكل socket.
  2. (2) مع stream socket و buffer غير فاضية، zero معناها إغلاق إرسال من الطرف الآخر بعد استهلاك الداتا.
  3. (3) read ممكن ترجع جزء من message أوكذا message؛ لازم protocol يحدد الحدود.

في edge-triggered epoll محتاج تتعامل صح مع nonblocking reads لحد EAGAIN؛ التطبيق العادي يفضل يستخدم .NET APIs بدل إعادة بناء event loop. مرجع epoll.

#اختياري: File descriptors و Handles و LimitsBonusOptional: file descriptors, handles and limits

اختياري بس بيفرق: مش هيتسأل فيه في كل انترفيو، بس معرفته بتعمّق فهمك وبتميّزك عن غيرك.

ملف مفتوح أو socket مش مجرد managed object؛ وراه resource. على Unix، file descriptor رقم في process table يشير لـ open resource؛ على Windows فيه handles مع access rights وآليات خاصة. المقبض مش pointer عادي ولاid دائم؛ أرقامه ممكن تتعاد بعد الإغلاق.

نسيان Dispose ممكن يستهلك limits حتى لو managed heap صغيرة. finalizers ممكن تعمل cleanup لاحقاً لبعض wrappers، لكن التوقيت مش مضمون، وبعض الموارد مش ليها finalizer أصلاً. استخدم using أو await using و SafeHandle في native interop المناسب.

المثال كامل لـ console app بيكتب file؛ -8 و line ending صريحين علشان النتيجة مستقلة عن المنصة.

using System.Text;

var path = Path.Combine(Path.GetTempPath(), $"invoice-{Guid.NewGuid():N}.txt");
await using (var file = new FileStream(path, FileMode.CreateNew,
    FileAccess.Write, FileShare.None, 4096, FileOptions.Asynchronous)) // (1)
{
    var bytes = Encoding.UTF8.GetBytes("Invoice total: 100 EGP\n");
    await file.WriteAsync(bytes); // (2)
} // (3)
Console.WriteLine(path);
🧾 شرح الكود
  1. (1) open file جديدة ومنع مشاركة متعارضة. Path.Combine بدل تركيب separators يدوياً.
  2. (2) كتابة async لا تعني ضمان وصول الداتا للـ physical disk وقت اكتمالها؛ durability عقد منفصل.
  3. (3) DisposeAsync تقفل المورد حتى لو الكتابة فشلت؛ الملف نفسه لسه موجود ومش اتمسح.

عند «too many open files»، افحص عدد descriptors ومصادرها و limits والـ leak قبل رفع الحد. sockets و pipes و epoll instances كمان بتستهلك descriptors. الـ diagnostic tools نفسها ممكن تكون غايبة من minimal container، فخطط للتشخيص من host أو debug image.

#اختياري: Signals و Graceful shutdown في containersBonusOptional: signals and graceful container shutdown

اختياري بس بيفرق: مش هيتسأل فيه في كل انترفيو، بس معرفته بتعمّق فهمك وبتميّزك عن غيرك.

deploy بيوقف process وهي ممكن تكون بتعالج طلب. Linux container runtime عادة بيبعت ، وبعد grace period ممكن . Generic Host مع ConsoleLifetime بيبدأ shutdown عند SIGTERM؛ SIGKILL مش قابل للالتقاط ولا يضمن finally. shell wrapper ممكن يمنع وصول signal لو مش بيعمل exec صح.

المثال Program.cs كامل لـ 10. notification callback قصيرة للـ logs؛ التنضيف async الحقيقي يتحط في hosted service StopAsync أو disposal، مع deadline.

var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<HostOptions>(options =>
    options.ShutdownTimeout = TimeSpan.FromSeconds(20)); // (1)
var app = builder.Build();

app.Lifetime.ApplicationStopping.Register(() => // (2)
    app.Logger.LogInformation("Shutdown requested; draining work"));

app.MapGet("/", () => "Ready");
await app.RunAsync(); // (3)
🧾 شرح الكود
  1. (1) host deadline جزء من الخطة؛ خلي container termination grace أكبر بما يكفي للتوجيه والـ drain. الكود مش بيمنع kill قهري.
  2. (2) ApplicationStopping واحدة من إشارات IHostApplicationLifetime. Register callback synchronous، مش مكان async void.
  3. (3) الـ host بيدير lifecycle. queue workers توقف سحب رسائل جديدة وتكمل أوترجع in-flight work بأمان.

اسحب instance من routing، وخلّي processing لأن crash ممكن يحصل في أي وقت. shutdown مش بديل عن durable queue و . Generic Host lifecycle.

#اختياري: cgroups و Namespaces و Windows مقابل LinuxBonusOptional: cgroups, namespaces, Windows and Linux

اختياري بس بيفرق: مش هيتسأل فيه في كل انترفيو، بس معرفته بتعمّق فهمك وبتميّزك عن غيرك.

Linux containers مبنية على mechanisms في kernel، مش نسخة كاملة لكل container. namespaces بتغير رؤية resources زي process IDs والشبكة والـ mounts؛ cgroups بتجمع processes لحساب الموارد وتحديد و memory وغيرها. namespaces مش resource limits، و cgroups مش network .

CPU limit ممكن يعمل throttling حتى لو الـ host عنده CPU فاضية خارج الحصة. memory limit ممكن تؤدي لـ OOM kill حسب الظروف. راقب cgroup usage مش managed heap بس، وماتكتبش paths ثابتة لقراءة cgroup files من غير فهم version و mount layout. مرجع cgroup v2.

الفرق العملياللي يهم developer
Paths و caseLinux غالباً case-sensitive و Windows غالباً case-insensitive؛ خليك مطابق لأسماء الملفات واستخدم Path
Line endingsLF مقابل CRLF؛ اضبط .gitattributes، وانتبه لـ shell scripts و shebang
PermissionsLinux UID و GID و mode bits مقابل Windows ACLs؛ مش كل فولدر writable
Service managementWindows Service Control Manager مقابل systemd؛ الاتنين محتاجين identity و restart policy و logs
Native dependencies مقابل shared libraries؛ راجع RID و architecture و globalization و time zones

متفترضش إن كل Windows filesystem بنفس case rules أوكل Linux filesystem بنفس capabilities. اختبر على deployment target في ، وماتعتمدش على drive letters أو registry أو Windows-only libraries في كود لازم يشتغل على Linux. containers مش عزل ؛ kernel مشتركة، وتقليل privileges و capabilities مهم.

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

راجع فهمك

ليه الاختيار ده مناسب؟ إمتى ممكن ماينفعش؟ وإيه اللي هيتغير لو الحمل زاد أو ظهر فشل؟

25.1What is the difference between a process, a thread and a Task?Junior

process موارد وعنوان ذاكرة، و thread تنفيذ جوّاها، و Task تمثيل اكتمال عملية. async مش محتاجة thread مستقلة لكل انتظار.

الإجابة النموذجية (English)

I view a process as an operating-system resource and address-space boundary, and a thread as an execution path inside it with its own stack and registers. Threads share process memory. A Task is a representation of an operation and its completion, not a dedicated thread. tasks often run on pooled threads, while asynchronous can remain pending without one thread blocked for each operation. The distinction matters when diagnosing scaling and resource usage.

25.2What are the main regions of process memory?Junior

code و data و heaps و stack لكل thread و mapped regions. النموذج تعليمي، والـ managed heap جزء بس من footprint.

الإجابة النموذجية (English)

I think in terms of executable code, data, heaps, per-thread stacks and mapped regions such as libraries and files. In , the managed heap is only part of the process footprint; native , code and thread stacks also matter. This is a conceptual layout rather than a fixed address ordering. I avoid saying all value types live on the stack because object fields, and captured async state provide clear counterexamples.

25.3Why can too many threads reduce performance?Mid

stacks و context switches و cache misses و contention. اكتر من runnable thread مش معناها cores أكتر.

الإجابة النموذجية (English)

I expect extra threads to help only when there is useful parallel work or unavoidable waiting they can overlap. Beyond that point, stacks consume memory, runnable threads compete for , and context switching harms locality. Shared locks may become more contended too. I measure and tail rather than equating thread count with capacity. For -heavy services, genuine async usually scale better than creating more threads to wait on external operations.

25.4Does every await cause a context switch?Mid

لأ؛ task مكتملة بتكمل فوراً. continuation بعد تعليق مش لازم نفس thread، و scheduling مختلف عن compiler state machine.

الإجابة النموذجية (English)

I do not assume a context switch at every await. If the awaitable has already completed, execution can continue synchronously. Otherwise the method records a continuation and returns control, and resumption depends on the scheduler and any captured context. That compiler-generated state-machine transition is not identical to an operating-system thread switch. In I also avoid assuming the continuation resumes on the original thread, since there is normally no request synchronization context requiring that.

25.5What is preemptive scheduling?Junior

الـ يقدر يوقف thread ويشغل غيرها من غير ما تستأذنه. priorities و time slices policies مش guarantees ثابتة.

الإجابة النموذجية (English)

I describe preemptive scheduling as the taking execution time away from a running thread so another can run. A thread does not have to voluntarily yield for that to happen. Scheduling decisions depend on priority, readiness, policy and available CPUs. I therefore protect shared state rather than assuming a short sequence cannot be interrupted. Raising a thread's priority does not make the operation atomic or guarantee a specific completion order.

25.6When would you use a mutex, semaphore or spinlock?Mid

لملكية حصرية، و لعدد تصاريح، و spinlock لانتظار قصير جداً بعد قياس. SemaphoreSlim async داخل process.

الإجابة النموذجية (English)

I use a for exclusive ownership when its thread-affinity and platform semantics fit, and a to limit the number of concurrent participants. For in-process async coordination, SemaphoreSlim provides an awaitable wait without holding a blocked thread. I reserve spinlocks for specialized low-level cases where measured waits are extremely short. Spinning around wastes , and holding a thread-owned mutex across await is unsafe because the continuation can run on another thread.

25.7What are the four Coffman deadlock conditions?Mid

mutual exclusion، و hold and wait، و no preemption، و circular wait. كسر شرط زي ترتيب locks ثابت يمنع النوع ده من .

الإجابة النموذجية (English)

I remember mutual exclusion, hold and wait, no preemption, and circular wait. Together they make classical resource possible, although their presence does not prove one has occurred. I usually prevent circular wait through a consistent acquisition order and reduce hold-and-wait with smaller critical sections. Timeouts can provide a failure path, but only if code releases what it already holds and handles partial work. Async waits can also form dependency cycles.

25.8How do deadlock, starvation and livelock differ?Senior

مفيش تقدم بسبب انتظار دائري؛ starvation شغل مش بياخد فرص؛ livelock نشاط من غير تقدم. كل واحد محتاج تشخيص مختلف.

الإجابة النموذجية (English)

I distinguish them by progress. In , participants cannot progress because of a dependency cycle. In starvation, some work receives insufficient access to or another resource while other work continues. In livelock, participants keep reacting or retrying but fail to make useful progress. I inspect waits, scheduling and retry behavior accordingly. Adding retries may help neither deadlock nor livelock and can make contention worse, so I first identify which progress failure is occurring.

25.9What is virtual memory?Junior

address space مترجمة لصفحات فعلية أو backing storage، بتوفر عزل وتحميل عند الحاجة. virtual size مش مستخدمة.

الإجابة النموذجية (English)

I see virtual memory as the address space presented to a process, with hardware and translation mapping it to physical memory or other backing. It supports , protection, sharing and demand loading. Reserving virtual address space does not immediately consume the same amount of . I therefore distinguish virtual size, committed and resident memory when diagnosing growth, rather than declaring a leak from one large address-space number.

25.10Does a page fault always mean a disk read or an error?Mid

لأ؛ valid demand page ممكن zero-fill أو mapping موجود. major fault ممكن يحتاج storage، و invalid access ممكن يفشل.

الإجابة النموذجية (English)

I do not treat every page fault as a bug or disk read. The may be handling valid demand , zero-filling a page or attaching a page already available in memory. Other faults require storage access and can be much more expensive. An invalid or prohibited access can instead fail the operation or process. I examine fault types and memory pressure together, because a high count without context is not a complete diagnosis.

25.11Why might process memory stay high after a GC?Senior

runtime تحتفظ بسعة، و native memory و stacks و mappings مش كلها تحت . working set مش live managed objects.

الإجابة النموذجية (English)

I separate live managed objects from retained runtime capacity and total resident process memory. The may reclaim objects without immediately returning all capacity to the , and the process also owns stacks, native , mappings and code. I compare managed metrics with process and container metrics before concluding there is a managed leak. A stable heap with growing resident memory sends me toward native resources and mappings rather than repeated forced collections.

25.12Is Server GC always better for an ASP.NET Core service?Senior

مش ضمان؛ قيس و والـ memory تحت limits الحقيقية. افحص الوضع الفعلي بدل افتراض ثابت.

الإجابة النموذجية (English)

I treat Server as a -oriented option rather than an automatic win. The web requests it by default, but actual behavior depends on runtime configuration and available resources. In small or densely packed containers, its memory and scheduling trade-offs may differ from a large dedicated server. I measure representative load under real and memory limits, inspect the active mode and avoid tuning GC before addressing patterns and workload bottlenecks.

25.13How do epoll and IOCP relate to .NET async I/O?Senior

epoll readiness، و completion. runtime بيحول تفاصيلهم لعمليات awaitable؛ مش كل async ليها نفس التنفيذ.

الإجابة النموذجية (English)

I think of epoll as readiness notification on Linux and as completion notification for supported Windows . The runtime uses platform facilities behind its socket so application code can await operations without dedicating a blocked thread to each socket. I avoid generalizing that to every async API, because file I/O and provider implementations vary. The compiler's async state machine observes completion; it is not itself the operating-system event loop.

25.14Why does IDisposable matter if .NET has garbage collection?Mid

لعمر managed memory، و Dispose لإطلاق موارد زي descriptors و connections في وقت معروف. finalizer مش توقيت مضمون.

الإجابة النموذجية (English)

I use disposal for deterministic release of resources such as file descriptors, sockets and database connections. Garbage collection manages managed-object memory, but that does not provide timely resource cleanup. Some wrappers have finalizers as a fallback, yet waiting for them can exhaust limits before memory pressure triggers collection. I use using or await using according to the resource contract and avoid relying on process exit as the normal cleanup strategy.

25.15What happens when a Linux container receives SIGTERM?Senior

Generic Host العادي يبدأ shutdown، وتشتغل lifetime notifications و StopAsync. grace period لو خلصت ممكن من غير cleanup.

الإجابة النموذجية (English)

I expect the normal Generic Host with ConsoleLifetime to begin graceful shutdown when it receives . The application stops accepting or acquiring work and hosted services receive their shutdown opportunity within a deadline. I make sure signals reach the process, configure enough container grace and keep callbacks short. If the grace expires, may terminate it without cleanup, so durable state, retries and must also handle abrupt failure.

25.16What roles do namespaces and cgroups play in Linux containers?Mid

namespaces للعزل في رؤية resources؛ cgroups لحساب وتحديد الموارد. kernel مشتركة ومش كاملة.

الإجابة النموذجية (English)

I use namespaces to explain isolated views of resources such as process IDs, networking and mounts. Cgroups provide resource grouping, accounting and controls such as and memory limits. These mechanisms complement each other but solve different problems. Containers still share the host kernel, so I also reduce privileges and capabilities. When diagnosing performance I inspect quota throttling and cgroup memory rather than assuming the application can use every resource visible on the host.

اختبر نفسك

إجابات الاختبار وعلامات إكمال المحاور بتتحفظ على المتصفح ده، ومش بتتنقل لأجهزة تانية.

النتيجة: 0 / 0

A pending socket Task must have which dedicated resource?

الـ Task بتمثل اكتمال عملية، مش thread خاصة.

Where does a struct field inside a managed class instance live?

مكان value type حسب سياق تخزينها، مش اسم النوع بس.

Which change breaks circular wait for two account locks?

ترتيب الموارد الثابت يمنع دائرة اكتساب الأقفال.

Which statement about page faults is correct?

zero-fill أوصفحة موجودة ممكن يحلوا fault من غير storage.

What does epoll primarily report?

readiness بتقول إن محاولة ممكن تتعمل من غير انتظار.

A service hits its open-file limit while managed heap remains small. First suspect?

descriptors مورد مستقل عن حجم managed objects.

Which signal cannot be caught for graceful cleanup?

kill قهري مش بيدي فرصة finally أو StopAsync.

Which mechanism primarily accounts for and limits Linux container resources?

namespaces للرؤية المعزولة، و cgroups للموارد.

What does GC heap hard limit fail to cap directly?

process footprint أوسع من managed heap.

Why can an app work on Windows but fail to find files on Linux?

طابق case واستخدم Path واختبر على نفس المستهدفة.