mutex — מודול mutex

המודול mutex מספק פרימיטיב של מניעה הדדית (mutual-exclusion) להגנה על קטעים קריטיים של קוד או נתונים משותפים מפני גישה מקבילה על ידי שגרת שירות פסיקה (interrupt service routine) וה-thread הראשי.

רכישה ושחרור של נעילה מבוצעים באמצעות context manager (משפט with), שנחסם עד שה-mutex זמין. מסופקת גם מתודה לא-חוסמת Mutex.test().

דוגמה:

from mutex import Mutex

mtx = Mutex()

# Acquire for a critical section (blocks if already held).
with mtx:
    # ... protected code, e.g. shared buffer access ...
    pass

# Or try without blocking.
if mtx.test():
    try:
        # ... protected code ...
        pass
    finally:
        mtx.release()

class Mutex – אובייקט mutex

class mutex.Mutex

יוצרת אובייקט mutex לא-נעול.

release() None

משחררת את ה-mutex. מעלה mutex.MutexException אם ה-mutex אינו נעול כעת.

test() bool

מנסה לרכוש את ה-mutex באופן לא-חוסם. מחזירה True בהצלחה ו-False אם ה-mutex כבר נעול.

כדי לרכוש את ה-mutex באופן חוסם, השתמשו במופע כ-context manager (משפט with). ה-mutex משוחרר אוטומטית ביציאה.

חריגות

exception mutex.MutexException

תת-מחלקה של OSError. מועלית על ידי Mutex.release כאשר ה-mutex כבר לא-נעול.