التنافي المتبادل (sync.Mutex)
التنافي المتبادل (sync.Mutex)
رأينا كيف تُعدّ القنوات وسيلة رائعة للاتصال بين مسارات التنفيذ الخفيفة.
لكن ماذا لو لم نحتج إلى الاتصال؟ ماذا لو أردنا فقط التأكد من أن مسار تنفيذ خفيفًا واحدًا فقط يمكنه الوصول إلى متغير في كل مرة لتجنب التعارضات؟
يُسمّى هذا المفهوم التنافي المتبادل، والاسم المتعارف عليه لبنية البيانات التي توفره هو قفل التنافي المتبادل.
توفر مكتبة Go القياسية التنافي المتبادل باستخدام
sync.Mutex وطريقتيه:
LockUnlock
يمكننا تحديد كتلة من الشيفرة لتُنفّذ في ظل التنافي المتبادل بإحاطتها
باستدعاءَي Lock وUnlock كما هو موضح في الطريقة Inc.
يمكننا أيضًا استخدام defer لضمان تحرير قفل التنافي المتبادل كما في الطريقة Value.
النص الأصلي بالإنجليزية
sync.Mutex
We've seen how channels are great for communication among goroutines.
But what if we don't need communication? What if we just want to make sure only one goroutine can access a variable at a time to avoid conflicts?
This concept is called mutual exclusion, and the conventional name for the data structure that provides it is mutex.
Go's standard library provides mutual exclusion with
sync.Mutex and its two methods:
LockUnlock
We can define a block of code to be executed in mutual exclusion by surrounding it
with a call to Lock and Unlock as shown on the Inc method.
We can also use defer to ensure the mutex will be unlocked as in the Value method.
هذا الدرس للقراءة فقط؛ جرّب المثال في الدرس التالي.