Exemplo n.º 1
0
from threading import Semaphore
from lightswitch import LightSwitch

empty = Semaphore(1)
maleSwitch = LightSwitch()
femaleSwitch = LightSwitch()
maleMultiplex = Semaphore(3)
femaleMultiplex = Semaphore(3)
turnstile = Semaphore(1)


def female():
    turnstile.acquire()
    femaleSwitch.lock(empty)
    turnstile.release()

    femaleMultiplex.acquire()
    # Use the bathroom
    femaleMultiplex.release()

    femaleSwitch.unlock(empty)


def male():
    turnstile.acquire()
    maleSwitch.lock(empty)
    turnstile.release()

    maleMultiplex.acquire()
    # Use the bathroom
    maleMultiplex.release()
# Search-insert-delete
from threading import *
from lightswitch import LightSwitch

searcherSwitch = LightSwitch()
inserterSwitch = LightSwitch()

inserter = Semaphore(1)
searcher = Semaphore(1)
deleter = Semaphore(1)

mutex = Semaphore(1)


def searcher_f():
    searcherSwitch.lock(searcher)
    # Search through list
    searcherSwitch.unlock(searcher)


def inserter_f():
    inserterSwitch.lock(deleter)
    inserter.acquire()
    # Insert into list
    inserter.release()
    inserterSwitch.unlock(deleter)


def deleter_f():
    deleter.acquire()
    inserter.acquire()
Exemplo n.º 3
0
# Readers-Writers with Writer-priority
from threading import *
from lightswitch import LightSwitch

nr = 3000
nw = 10

database = 0

readSwitch = LightSwitch()
writeSwitch = LightSwitch()
noReaders = Semaphore(1)
noWriters = Semaphore(1)


def reader():
    noReaders.acquire()
    readSwitch.lock(noWriters)
    noReaders.release()

    # Reading
    print(database)

    readSwitch.unlock(noWriters)


def writer():
    writeSwitch.lock(noReaders)
    noWriters.acquire()

    # Critical section
Exemplo n.º 4
0
# Readers-Writers
from threading import *
from lightswitch import LightSwitch

nr = 3000
nw = 10

database = 0

readSwitch = LightSwitch()
roomEmpty = Semaphore(1)
turnstile = Semaphore(1)


def reader():
    turnstile.acquire()
    turnstile.release()
    readSwitch.lock(roomEmpty)

    # Reading
    print(database)

    readSwitch.unlock(roomEmpty)


def writer():
    turnstile.acquire()
    roomEmpty.acquire()

    # Nobody in the room: Writing
    global database
Exemplo n.º 5
0
 def testMode(self):
     unit=LightSwitch()
     unit.setMode(LightSwitch.SWITCH_ON)
     self.assertEqual(unit.getMode(), LightSwitch.SWITCH_ON)        
     unit.setMode(LightSwitch.SWITCH_OFF)
     self.assertEqual(unit.getMode(), LightSwitch.SWITCH_OFF)
Exemplo n.º 6
0
 def testInit(self):
     unit= LightSwitch()
     self.assertEqual(unit.getMode(), LightSwitch.SWITCH_OFF)
Exemplo n.º 7
0
    def testvalidMode(self):
        unit=LightSwitch()
        with self.assertRaises(Exception) as context:
            unit.setMode(3)

        self.assertTrue("Value must be either 0 or 1" in str(context.exception))