0

I'm currently using a simple program to test the functionality of lists when it comes to threading for a separate networking assignment I am working on. My main goal was to see if lists could be global if created at the beginning, outside of all of the functions, and to make sure locks worked how I expected them to.

I currently just have a project intended to allow me to append items onto a list and then have another thread read the list back to me every few seconds to see if those changes went through. My most recent issue is I didn't exactly understand why the args passed to the target function had to be an iterable rather than just an object.

I also found it kind of strange that you have to explicitly pass your lock to every function. Currently it gives me no errors but there is some sort of logic error that makes the program just sit and do nothing.

import threading
import time

myList = ["Default"]
lock = threading.Lock()

def fillList(lock):
    while True:
    
        ("Append item to list: ")

        lock.acquire()
        myList.append(input())
        lock.release()


def readList(lock):
    while True:
    
        time.sleep(5)
    
        lock.acquire()
        for i in myList:
            print(i)
        lock.release()

t1 = threading.Thread(target=fillList, args=[lock])
t2 = threading.Thread(target=readList, args=[lock])

t1.start()
t2.start()
t1.join()
t2.join()

This is what I've attempted so far and it seemed like a simple idea at first but I have ran into many pitfalls. A lot of my design on my networking project hinged on using some parallels lists to keep a lot of user data but if another data structure might be better I am willing to be convinced.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • The problem is there's too tight a loop in your `fillList()` function, so the other one hardly ever get a chance to run (threads really don't run concurrently in Python due to the GIL). Adding a `time.sleep(.25)` after the `lock.release()` and should work. An alternative to passing the lock to every function would be to create a "thread-safe" list object that had it's own lock which it used automatically every time one of its mutating methods was called. – martineau Sep 27 '20 at 23:30
  • You can make the built-in list container thread-safe: See [How to make built-in containers (sets, dicts, lists) thread safe?](https://stackoverflow.com/questions/13610654/how-to-make-built-in-containers-sets-dicts-lists-thread-safe). – martineau Sep 27 '20 at 23:32

0 Answers0