def thread(settings, results): global TEO duration = 5 semaphore = Semaphore( resource_name='testing', rabbitmq_username=settings['username'], rabbitmq_password=settings['password'], rabbitmq_ip=settings['ip'], rabbitmq_port=settings['port'], rabbitmq_api_port=settings['api_port'], rabbitmq_virtual_host=settings['virtual_host']) try: TEO += 1 order = TEO start = time.time() semaphore.acquire() delta = time.time() - start print 'Thread {} waited {} seconds for lock. OK!'.format(order, delta) """First thread should acquire lock very quickly. Threads 2 and 3 are waiting at least 5 and 10 seconds respectively. """ switch = {1: (delta, 1), 2: (duration, delta), 3: (duration*2, delta)} results.append(switch[order][0] < switch[order][1]) time.sleep(duration) # accesing hypothetical resource here finally: semaphore.release()
def setUp(self): self.client = Redis() self.client.flushdb() self.semaphore = Semaphore(self.client, "test-semaphore") self.max_size = 3
def setUp(self): self.client = Redis(decode_responses=True) self.client.flushdb() self.semaphore = Semaphore(self.client, "test-semaphore") self.max_size = 3
def main(): Ready = Queue(maxsize=1) # 当前就绪进程 Buffer = Queue(maxsize=8) # 定义缓冲区 Mutex = Semaphore(1, "Mutex") # 互斥信号量 BufferEmpty = Semaphore(8, "BufferEmpty") # Empty信号量 BufferFull = Semaphore(0, "BufferFull") # Full 信号量 app = QApplication(sys.argv) window = Mywindow(Ready, Buffer, Mutex, BufferEmpty, BufferFull) window.paintEngine() window.show() sys.exit(app.exec_())
class Ball: def __init__(self): self.time_count = 0 self.sem = Semaphore() def get_the_ball(self, thread): while (self.time_count < 45): self.sem.down(thread) # down if thread.was_sleeping: thread.was_sleeping = False else: # CRITICAL REGION time.sleep(random.randint(1, 2)) # min 1 sec / max 2 sec # Leave critical region self.left_the_ball(thread) self.time_count += 1 if not self.sem.is_active() and self.sem.has_someone_sleeping(): self.sem.up() def left_the_ball(self, thread): print(thread.get_name(), "left the ball!") self.sem.up() # up time.sleep(random.randint(1, 2))
def test_semaphore(): filename = 'foo.txt' try: semaphore = Semaphore(time_limit=5) input_process = DummyInputProcess('foo', semaphore._input_queue, semaphore._logger) input_process.topic_filter = DummyTopicFilter() file_handler = FileHandler('barhandler', filename) semaphore.add_input_process(input_process) semaphore.replace_middleware_process(DummyMiddleProcess) semaphore.add_output_handler(file_handler) with pytest.raises(SemaphoreTimeLimitInterrupt): semaphore.run() finally: if os.path.isfile(filename): os.remove(filename)
def setUp(self): with open('tests.yaml') as f: self.settings = yaml.load(f) self.semaphore = Semaphore( resource_name='testing', max_connections=1, rabbitmq_username=self.settings['username'], rabbitmq_password=self.settings['password'], rabbitmq_ip=self.settings['ip'], rabbitmq_port=self.settings['port'], rabbitmq_api_port=self.settings['api_port'], rabbitmq_virtual_host=self.settings['virtual_host']) time.sleep(2)
def test_semaphore(): filename = 'foo.txt' try: semaphore = Semaphore(time_limit=10) log_handler = logging.StreamHandler(sys.stderr) log_handler.setLevel(logging.DEBUG) semaphore._logger.addHandler(log_handler) input_process = DummyInputProcess('foo', semaphore._input_queue, semaphore._logger) input_process.topic_filter = DummyTopicFilter() file_handler = FileHandler('barhandler', filename) semaphore.add_input_process(input_process) semaphore.replace_middleware_process(DummyMiddleProcess) semaphore.add_output_handler(file_handler) semaphore.run() finally: if os.path.isfile(filename): os.remove(filename)
def doit(endpoint_url, lock_path): while True: s = Semaphore(service_name=lock_path, concurrency_limit=1, host_url=endpoint_url) print('Attempting to get the lock') s.acquire(True) print('I has the lockz!!!') time.sleep(3) print('Releasing lock') time.sleep(1) s.release()
def test_semaphore(self): s = Semaphore() def run(sem, id): sem.acquire() print("thread={0} getting semaphore".format(id)) sem.release() t1 = Thread(target=run, args=( s, "thread1", )) t2 = Thread(target=run, args=( s, "thread2", )) t2.start() t1.start()
class SemaphoreTest(unittest.TestCase): def setUp(self): with open('tests.yaml') as f: self.settings = yaml.load(f) self.semaphore = Semaphore( resource_name='testing', max_connections=1, rabbitmq_username=self.settings['username'], rabbitmq_password=self.settings['password'], rabbitmq_ip=self.settings['ip'], rabbitmq_port=self.settings['port'], rabbitmq_api_port=self.settings['api_port'], rabbitmq_virtual_host=self.settings['virtual_host']) time.sleep(2) def tearDown(self): self.semaphore.destroy() def test_initialization(self): self.assertTrue(self.semaphore.channel.is_open) self.assertEqual(self.semaphore.get_current_max(), 1) def test_change_limit(self): self.semaphore.change_limit(100) time.sleep(2) self.assertEqual(self.semaphore.get_current_max(), 100) def test_multithreading(self): results = [] t1 = threading.Thread(target=thread, args=(self.settings, results)) t2 = threading.Thread(target=thread, args=(self.settings, results)) t3 = threading.Thread(target=thread, args=(self.settings, results)) t1.start() t2.start() t3.start() t1.join() t2.join() t3.join() for result in results: self.assertTrue(result)
from time import sleep from semaphore import Semaphore semaphore = Semaphore() semaphore.start() sleep(0.5)
def run(): semaphore = Semaphore(period=5, cross_time=3) loop = asyncio.get_event_loop() loop.create_task(transition(semaphore)) loop.run_forever()
def __init__(self): Semaphore.__init__(self, 1) self.player = None
import random from threading import Thread from semaphore import Semaphore ok2 = (Semaphore(1), Semaphore(0)) def pre(n): ok2[n].P() def post(n): ok2[1 - n].V() def bohm(n): while (True): pre(n) print(n) post(n) if __name__ == "__main__": bohm0 = Thread(target=bohm, name="bohm-0", args=(0, ), daemon=True) bohm1 = Thread(target=bohm, name="bohm-1", args=(1, ), daemon=True) threads = random.sample([bohm0, bohm1], 2) [thread.start() for thread in threads] [thread.join() for thread in threads]
class TestSemaphore(unittest.TestCase): def setUp(self): self.client = Redis(decode_responses=True) self.client.flushdb() self.semaphore = Semaphore(self.client, "test-semaphore") self.max_size = 3 def tearDown(self): self.client.flushdb() def test_raise_type_error_when_max_size_not_set(self): with self.assertRaises(TypeError): self.semaphore.acquire("huangz") def test_set_max_size_and_get_max_size(self): self.semaphore.set_max_size(self.max_size) self.assertEqual( self.semaphore.get_max_size(), self.max_size ) self.semaphore.set_max_size(10) self.assertEqual( self.semaphore.get_max_size(), 10 ) def test_get_current_size(self): self.semaphore.set_max_size(self.max_size) self.assertEqual( self.semaphore.get_current_size(), 0 ) self.semaphore.acquire("huangz") self.assertEqual( self.semaphore.get_current_size(), 1 ) self.semaphore.release("huangz") self.assertEqual( self.semaphore.get_current_size(), 0 ) def test_acquire_and_release_works(self): self.semaphore.set_max_size(self.max_size) self.assertTrue( self.semaphore.acquire("huangz") ) self.assertTrue( self.semaphore.release("huangz") ) def test_acquire_return_false_when_reach_max_size(self): self.semaphore.set_max_size(self.max_size) for i in range(self.max_size): self.assertTrue( self.semaphore.acquire(i) ) self.assertFalse( self.semaphore.acquire("you acquire too much semaphore!") ) def test_release_return_false_when_identity_not_match(self): self.semaphore.set_max_size(self.max_size) self.semaphore.set_max_size(self.max_size) self.semaphore.acquire("huangz") self.assertFalse( self.semaphore.release("wrong identity") )
def __init__(self): self.time_count = 0 self.sem = Semaphore()