0
from threading import Lock
from threading import Thread

class LockedList(list):
    def __init__(self, *args, **kwargs):
        self._lock = Lock()
        super(LockedList, self).__init__(*args, **kwargs)

    def remove(self, elem):
        with self._lock:
            super(LockedList, self).remove(elem)

    def insert(self, i, elem):
        with self._lock:
            super(LockedList, self).insert(i, elem)

    def __contains__(self, elem):
        with self._lock:
            super(LockedList, self).__contains__(elem)


list = [2, 3, 4]
for i in range(100):
    t1 = threading.Thread(target=list.insert(i, i))
    if i % 2 == 0:
        t2 = threading.Thread(target=list.remove(i))

#10 output
for i in range(len(list)):
    if i % 10 == 0 and i != 0:
        print()
    print(list[i], end=' ')

I wrote this code for using locked_list decorator. But i don't know how to test it. Is it right code to test? I want to test list.insert() and list.remove() by using thread whether it causes race condition.

AcK
  • 2,063
  • 2
  • 20
  • 27
su00
  • 29
  • 5
  • `test list.insert() and list.remove() by using thread whether it causes race condition` - yes that seems like a good summary of what you’ve got to do. Write that code. – DisappointedByUnaccountableMod Oct 10 '20 at 08:41
  • @barny I edited the code. Is it right code to use decorated insert, remove? – su00 Oct 10 '20 at 09:08
  • Lists are thread-safe to begin with. Why do you need this? See [Are lists thread-safe?](https://stackoverflow.com/questions/6319207/are-lists-thread-safe). – Booboo Oct 10 '20 at 10:25
  • @Booboo I'm reading a book 'Learning concurrency in python'. In that book, it is explaining 'Lists are thread safe only in the way that access them.' So, lock mechanism is needed when using lists in multi-threaded program. – su00 Oct 10 '20 at 10:39
  • @Booboo so i modify list.insert() and list.remove(). – su00 Oct 10 '20 at 10:41

0 Answers0