Welcome, guest | Sign In | My Account | Store | Cart

This module provides a way to create a mutex which is valid for the system (i.e.: it can be seen by multiple processes).

Note that the mutex is kept until release_mutex() is called or when it's garbage-collected.

Python, 180 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# License: LGPL
#
# Copyright: Brainwy Software

'''
To use, create a SystemMutex, check if it was acquired (get_mutex_aquired()) and if acquired the
mutex is kept until the instance is collected or release_mutex is called.

I.e.:

mutex = SystemMutex('my_unique_name')
if mutex.get_mutex_aquired():
    print('acquired')
else:
    print('not acquired')
'''

import re
import sys
import tempfile
import traceback
import weakref

# Note: Null comes from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68205
NULL = Null()


def check_valid_mutex_name(mutex_name):
    # To be windows/linux compatible we can't use non-valid filesystem names
    # (as on linux it's a file-based lock).

    regexp = re.compile(r'[\*\?"<>|/\\:]')
    result = regexp.findall(mutex_name)
    if result is not None and len(result) > 0:
        raise AssertionError('Mutex name is invalid: %s' % (mutex_name,))

if sys.platform == 'win32':

    import os

    class SystemMutex(object):

        def __init__(self, mutex_name):
            check_valid_mutex_name(mutex_name)
            filename = os.path.join(tempfile.gettempdir(), mutex_name)
            try:
                os.unlink(filename)
            except:
                pass
            try:
                handle = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_RDWR)
                try:
                    try:
                        pid = str(os.getpid())
                    except:
                        pid = 'unable to get pid'
                    os.write(handle, pid)
                except:
                    pass  # Ignore this as it's pretty much optional
            except:
                self._release_mutex = NULL
                self._acquired = False
            else:
                def release_mutex(*args, **kwargs):
                    # Note: can't use self here!
                    if not getattr(release_mutex, 'called', False):
                        release_mutex.called = True
                        try:
                            os.close(handle)
                        except:
                            traceback.print_exc()
                        try:
                            # Removing is optional as we'll try to remove on startup anyways (but
                            # let's do it to keep the filesystem cleaner).
                            os.unlink(filename)
                        except:
                            pass

                # Don't use __del__: this approach doesn't have as many pitfalls.
                self._ref = weakref.ref(self, release_mutex)

                self._release_mutex = release_mutex
                self._acquired = True

        def get_mutex_aquired(self):
            return self._acquired

        def release_mutex(self):
            self._release_mutex()


# Below we have a better implementation, but it relies on win32api which we can't be sure
# the client will have available in the Python version installed at the client, so, we're
# using a file-based implementation which should work in any implementation.
#
#     from win32api import CloseHandle, GetLastError
#     from win32event import CreateMutex
#     from winerror import ERROR_ALREADY_EXISTS
#
#     class SystemMutex(object):
#
#         def __init__(self, mutex_name):
#             check_valid_mutex_name(mutex_name)
#             mutex = self.mutex = CreateMutex(None, False, mutex_name)
#             self._acquired = GetLastError() != ERROR_ALREADY_EXISTS
#
#             if self._acquired:
#
#                 def release_mutex(*args, **kwargs):
# Note: can't use self here!
#                     if not getattr(release_mutex, 'called', False):
#                         release_mutex.called = True
#                         try:
#                             CloseHandle(mutex)
#                         except:
#                             traceback.print_exc()
#
# Don't use __del__: this approach doesn't have as many pitfalls.
#                 self._ref = weakref.ref(self, release_mutex)
#                 self._release_mutex = release_mutex
#             else:
#                 self._release_mutex = NULL
#                 CloseHandle(mutex)
#
#         def get_mutex_aquired(self):
#             return self._acquired
#
#         def release_mutex(self):
#             self._release_mutex()

else:  # Linux
    import os
    import fcntl

    class SystemMutex(object):

        def __init__(self, mutex_name):
            check_valid_mutex_name(mutex_name)
            filename = os.path.join(tempfile.gettempdir(), mutex_name)
            try:
                handle = open(filename, 'w')
                fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except:
                self._release_mutex = NULL
                self._acquired = False
                try:
                    handle.close()
                except:
                    pass
            else:
                def release_mutex(*args, **kwargs):
                    # Note: can't use self here!
                    if not getattr(release_mutex, 'called', False):
                        release_mutex.called = True
                        try:
                            fcntl.flock(handle, fcntl.LOCK_UN)
                        except:
                            traceback.print_exc()
                        try:
                            handle.close()
                        except:
                            traceback.print_exc()
                        try:
                            # Removing is pretty much optional (but let's do it to keep the
                            # filesystem cleaner).
                            os.unlink(filename)
                        except:
                            pass

                # Don't use __del__: this approach doesn't have as many pitfalls.
                self._ref = weakref.ref(self, release_mutex)

                self._release_mutex = release_mutex
                self._acquired = True

        def get_mutex_aquired(self):
            return self._acquired

        def release_mutex(self):
            self._release_mutex()
Created by Fabio Zadrozny on Fri, 9 Jan 2015 (LGPL)
Python recipes (4591)
Fabio Zadrozny's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks