File: Synchronization.py

package info (click to toggle)
pyscard 1.6.10-2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 1,360 kB
  • ctags: 1,516
  • sloc: python: 6,387; ansic: 2,065; makefile: 2
file content (40 lines) | stat: -rw-r--r-- 1,124 bytes parent folder | download
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
"""
from Thinking in Python, Bruce Eckel
http://mindview.net/Books/TIPython

Simple emulation of Java's 'synchronized'
keyword, from Peter Norvig.
"""

from threading import RLock

def synchronized(method):
    def f(*args):
        self = args[0]
        self.mutex.acquire()
        # print method.__name__, 'acquired'
        try:
            return apply(method, args)
        finally:
            self.mutex.release()
            # print method.__name__, 'released'
    return f

def synchronize(klass, names=None):
    """Synchronize methods in the given class.
    Only synchronize the methods whose names are
    given, or all methods if names=None."""
    if type(names)==type(''):
            names = names.split()
    for (name, val) in klass.__dict__.items():
        if callable(val) and name != '__init__' and \
            (names == None or name in names):
                # print "synchronizing", name
                klass.__dict__[name] = synchronized(val)

# You can create your own self.mutex, or inherit
# from this class:
class Synchronization:
    def __init__(self):
        self.mutex = RLock()
#:~