Cooperation: Synchronization Tools التعاون: أدوات المزامنة

Solving the Race Condition. Understanding the Critical Section Problem, Mutex Locks, Semaphores, and Atomic Operations. حل حالة التسابق (Race Condition). فهم مشكلة القسم الحرج (Critical Section)، أقفال Mutex، Semaphores، والعمليات الذرية (Atomic Operations).

Race Condition Race Condition Critical Section (CS) Critical Section (CS) Peterson's Solution Peterson's Solution Mutex Locks Mutex Locks Semaphores Semaphores

The Core Problem المشكلة الجوهرية

Race Condition Race Condition (حالة التسابق)

A situation where several processes access and manipulate the same data concurrently, and the outcome depends on the particular order in which the access takes place. حالة تقوم فيها عدة عمليات بالوصول إلى نفس البيانات وتعديلها بشكل متزامن، وتعتمد النتيجة النهائية على الترتيب المحدد الذي تم فيه الوصول.

// Example: Counter++ vs Counter--
Process A (count++)
1. reg1 = count
2. reg1 = reg1 + 1
3. count = reg1
Process B (count--)
1. reg2 = count
2. reg2 = reg2 - 1
3. count = reg2

If these instructions interleave (e.g., A1, B1, A2, B2...), the final value of count will be wrong.

The Critical Section (CS) Problem مشكلة القسم الحرج (The Critical Section Problem)

A segment of code where the process accesses shared resources. جزء من الكود حيث تقوم العملية بالوصول إلى الموارد المشتركة.

do { entry section CRITICAL SECTION exit section REMAINDER SECTION } while (TRUE);
The 3 Requirements for a Solution: المتطلبات الثلاثة للحل:
  1. Mutual Exclusion:Mutual Exclusion (الاستبعاد المتبادل): If Process P is in CS, no other process can be in CS. إذا كانت العملية P في CS، لا يمكن لأي عملية أخرى أن تكون في CS.
  2. Progress:Progress (التقدم): If no one is in CS, and someone wants to enter, the selection cannot be postponed indefinitely. إذا لم يكن أحد في CS، وأراد أحدهم الدخول، فلا يمكن تأجيل الاختيار إلى أجل غير مسمى.
  3. Bounded Waiting:Bounded Waiting (الانتظار المحدود): There is a limit on how many times others can enter CS before a specific process is granted access (No starvation). هناك حد لعدد المرات التي يمكن للآخرين الدخول فيها إلى CS قبل منح الوصول لعملية محددة (منع المجاعة).

Solutions الحلول (Solutions)

Peterson's Solution (Software) Peterson's Solution (برمجياً)

A classic software-based solution for 2 processes. Uses two variables: `turn` and `flag`. حل برمجي كلاسيكي لعمليتين. يستخدم متغيرين: `turn` و `flag`.

flag[i] = true; turn = j; while (flag[j] && turn == j); // Busy Wait /* CRITICAL SECTION */ flag[i] = false;

Note: May not work on modern architectures due to instruction reordering. ملاحظة: قد لا يعمل على المعماريات الحديثة بسبب إعادة ترتيب التعليمات.

Hardware Support دعم الأجهزة (Hardware Support)

Modern systems provide special Atomic Instructions (Non-interruptible). توفر الأنظمة الحديثة تعليمات ذرية (Atomic Instructions) خاصة (غير قابلة للمقاطعة).

test_and_set() Reads a boolean value and sets it to TRUE atomically. يقرأ قيمة منطقية ويضبطها على TRUE بشكل ذري.
compare_and_swap() Compares content of memory with expected value; if equal, swaps it. يقارن محتوى الذاكرة بالقيمة المتوقعة؛ إذا تساويا، يبدلها.

OS Tools أدوات نظام التشغيل (OS Tools)

Mutex Locks Mutex Locks

Short for MUTual EXclusion. The simplest tool.
A process must `acquire()` the lock before entering CS and `release()` it after.
اختصار لـ MUTual EXclusion. أبسط أداة.
يجب على العملية استدعاء `acquire()` للقفل قبل دخول CS و `release()` بعد الخروج.

acquire() { while (!available); // Busy wait available = false; } release() { available = true; }

Often called "Spinlocks" because of busy waiting. تسمى غالباً "Spinlocks" بسبب الانتظار المشغول (Busy Waiting).

Semaphores Semaphores

More robust integer variable `S` accessed only via `wait()` (P) and `signal()` (V). متغير صحيح أكثر قوة `S` يتم الوصول إليه فقط عبر `wait()` و `signal()`.

  • Counting Semaphore:Counting Semaphore: Integer value unrestricted. Used for resource counting. قيمة صحيحة غير مقيدة. تستخدم لعد الموارد.
  • Binary Semaphore:Binary Semaphore: 0 or 1. Equivalent to Mutex. 0 أو 1. تكافئ الـ Mutex.
Avoiding Busy Wait:تجنب الانتظار المشغول:
Instead of spinning, a process can block itself and be placed in a waiting queue. `signal()` wakes it up. بدلاً من الدوران، يمكن للعملية حجب نفسها ووضعها في طابور انتظار. `signal()` توقظها.

Classic Synchronization Problems مشاكل المزامنة الكلاسيكية

1

Bounded-Buffer Problem Bounded-Buffer Problem

Producer generates data, Consumer eats it. Must synchronize access to the buffer (Full/Empty slots). المنتج يولد البيانات، والمستهلك يأكلها. يجب مزامنة الوصول إلى المخزن المؤقت (الخانات الممتلئة/الفارغة).

2

Readers-Writers Problem Readers-Writers Problem

Many readers can read simultaneously. Only one writer can write at a time (exclusive access). يمكن للعديد من القراء القراءة في نفس الوقت. كاتب واحد فقط يمكنه الكتابة في وقت واحد (وصول حصري).

3

Dining-Philosophers Problem Dining-Philosophers Problem

5 philosophers, 5 chopsticks. Need 2 to eat. How to prevent deadlock where everyone holds 1 stick? 5 فلاسفة، 5 عيدان طعام. يحتاج كل واحد إلى 2 ليأكل. كيف نمنع الجمود (Deadlock) حيث يمسك كل شخص بعود واحد؟

The Exam Vault خزنة الاختبار

Professor's Secrets & Trap Avoidance أسرار البروفيسور وتجنب الفخاخ

TRAP: Spinlock Usage فخ: استخدام Spinlock

"When is a Spinlock (Busy Wait) actually good?"
Answer: In Multiprocessor systems when the lock is held for a very short time. It avoids the expensive Context Switch required to put a process to sleep.
"متى يكون Spinlock (الانتظار المشغول) جيداً فعلاً؟"
الإجابة: في الأنظمة متعددة المعالجات عندما يتم الاحتفاظ بالقفل لفترة قصيرة جداً. هذا يتجنب تبديل السياق المكلف المطلوب لوضع العملية في حالة السكون.

TRAP: Deadlock vs Starvation فخ: Deadlock مقابل Starvation

Deadlock: Two or more processes are waiting indefinitely for an event that can only be caused by one of the waiting processes. (Everyone stuck).
Starvation: Indefinite blocking. A process waits forever but the system isn't frozen (others are proceeding).
Deadlock (الجمود): عمليتان أو أكثر تنتظران إلى أجل غير مسمى لحدث لا يمكن أن يسببه إلا إحدى العمليات المنتظرة. (الجميع عالق).
Starvation (المجاعة): الحجب غير المحدود. العملية تنتظر إلى الأبد لكن النظام ليس مجمداً (الآخرون يتقدمون).

SECRET: Semaphore Implementation سر: تنفيذ Semaphore

Semaphores themselves must be atomic. How do we ensure `wait()` and `signal()` don't have race conditions?
We implement them using ... Critical Sections (Spinlocks/Interrupt disabling) inside the Kernel! It's recursion all the way down.
الـ Semaphores نفسها يجب أن تكون ذرية. كيف نضمن أن `wait()` و `signal()` ليس لديهما شروط سباق؟
نقوم بتنفيذها باستخدام ... Critical Sections (Spinlocks/تعطيل المقاطعة) داخل النواة! إنها تكرارية حتى النهاية.

KEY CONCEPT: Atomic Variable مفهوم أساسي: Atomic Variable

Provides atomic updates on basic data types (integers, booleans) without explicit locks. Often used for counters.
Implemented via hardware CAS (Compare-And-Swap).
يوفر تحديثات ذرية لأنواع البيانات الأساسية (الأعداد الصحيحة، المنطقية) بدون أقفال صريحة. غالباً ما تستخدم للعدادات.
تنفذ عبر أجهزة CAS (Compare-And-Swap).