Esempio n. 1
0
    def test_multiple_readers(self):
        """Test non-exclusive access to readers"""

        rw_lock = RWLock()
        rw_buffer = ['A']

        threads = [Reader(rw_lock, rw_buffer, 0, 0.05),
                   Reader(rw_lock, rw_buffer, 0.01, 0),
                   Writer(rw_lock, rw_buffer, 0.02, 0.02, 'Z'),
                   Reader(rw_lock, rw_buffer, 0.03, 0)]

        for th in threads:
            th.start()
        for th in threads:
            th.join()

        self.assertEqual(rw_buffer, ['Z'])
        self.assertEqual(threads[0].rdata, ['A'])
        self.assertEqual(threads[1].rdata, ['A'])
        self.assertEqual(threads[3].rdata, ['Z'])

        # Second reader started after the first one finishing
        # before it. This means there is no mutual exclusion
        # between readers.
        self.assertLess(threads[0].entry_time, threads[1].entry_time)
        self.assertGreater(threads[0].exit_time, threads[1].exit_time)
Esempio n. 2
0
    def test_exclusion_writers(self):
        """Test if only one writer can access the resource at the same time"""

        rw_lock = RWLock()
        rw_buffer = ['A']

        threads = [Reader(rw_lock, rw_buffer, 0, 0.02),
                   Writer(rw_lock, rw_buffer, 0.02, 0.03, 'Z'),
                   Writer(rw_lock, rw_buffer, 0.03, 0, 'X'),
                   Reader(rw_lock, rw_buffer, 0.04, 0)]

        for th in threads:
            th.start()
        for th in threads:
            th.join()

        self.assertEqual(rw_buffer, ['X'])
        self.assertEqual(threads[0].rdata, ['A'])
        self.assertEqual(threads[3].rdata, ['X'])

        # First writting lasts more than the time that the second
        # writer needs to access the critical section. But, the
        # second writer will wait till the first writer ends its work.
        self.assertLess(threads[1].entry_time, threads[2].entry_time)
        self.assertLess(threads[1].exit_time, threads[2].exit_time)

        # The last thread (a reader) will wait till the last writer ends.
        self.assertLess(threads[2].entry_time, threads[3].entry_time)
        self.assertLess(threads[2].exit_time, threads[3].exit_time)