ActiveState Code

Recipe 496865: z_sync.py


This recipe gives access to the Sync class. Objects created by the Sync class are meant to be used when trying to syncronize the execution of two or more threads. See z_service.py for more a simple example of how Sync objects can be used.

Python
 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
'''Support module for syncronizing threads.

This module allows access to the Sync class which can
allow automatic sycronization across several threads.'''

__version__ = 1.1

################################################################################

import thread

class Sync:

    'Sync(threads) -> new syncronizer object'

    def __init__(self, threads):
        'x.__init__(...) initializes x'
        self.__threads = threads
        self.__count = 0
        self.__main = thread.allocate_lock()
        self.__exit = thread.allocate_lock()
        self.__exit.acquire()

    def sync(self):
        'Automatically syncronizes threads.'
        self.__main.acquire()
        self.__count += 1
        if self.__count < self.__threads:
            self.__main.release()
        else:
            self.__exit.release()
        self.__exit.acquire()
        self.__count -= 1
        if self.__count > 0:
            self.__exit.release()
        else:
            self.__main.release()

################################################################################

if __name__ == '__main__':
    import sys
    print 'Content-Type: text/plain'
    print
    print file(sys.argv[0]).read()

Discussion

The following code gives one example of how Sync objects can be used. <pre> import os import random import sync import time

SLOTS = 10

def reader(slots): while True: if os.name == 'nt': os.system('cls') elif os.name == 'posix': os.system('clear') print str(slots)[1:-1]

def writer(slots, index, sleep): while True: if not random.randrange(100000): sleep.sync() time.sleep(5) slots[index] = (slots[index] + 1) % 10

def main(): slots = [0] * SLOTS sleep = sync.Sync(SLOTS) sync.thread.start_new_thread(reader, (slots,)) for index in range(SLOTS): sync.thread.start_new_thread(writer, (slots, index, sleep)) sync.Sync(2).sync()

if __name__ == '__main__': main() </pre>

Sign in to comment