'How do I make a thread print a list whenever it is updated?

I'm trying to make it so that the function foo() can continually wait until the array array has been changed so it can print it out.

I'm coming from C so there's a possibility I'm overcomplicating this. This is what I tried.

I have two condition variables, cv1 tells foo whether a change to an array has been made, and cv2 notifies when foo() is finished printing array.

Right now nothing happens. I think it's getting stuck in a loop. If anyone knows a simpler solution to this it would be appreciated.

import threading
import time
import logging

array = None
updated = False
terminate = False
finishedPrinting = False

def foo():
  with cv1:
    while True:
      while not updated and not terminate:
        cv1.wait()
      if terminate:
        return

      print array
      updated = False
      with cv2:
        logging.debug('Finished printing array')
        finishedPrinting = True
        cv2.notify()

cv1 = threading.Condition()
cv2 = threading.Condition()

with cv1:
  array = [1, 2, 3]
  updated = True
  cv1.notify()

with cv2:
  while not finishedPrinting:
    cv2.wait()
  finishedPrinting = False

with cv1:
  array = [5, 2, 1, 1]
  updated = True
  cv1.notify()

with cv2:
  while not finishedPrinting:
    cv2.wait()
  finishedPrinting = False

with cv1:
    terminate = True
    cv1.notify()

t1 = threading.Thread(name='thread', target=foo, args=(cv1, cv2))
t1.start()


Solution 1:[1]

The issue was that I had the creation of the thread at the bottom of the file when it should be at the beginning:

t1 = threading.Thread(name='thread', target=compress, args=(cv1, cv2))
t1.start()
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

with cv1:
  array = ['z','b','y','e','y','f','w','q','q']
  updated = True
  cv1.notify()
logging.debug('Updated')

with cv2:
  while not finishedProcessing:
    cv2.wait()
  finishedProcessing = False
logging.debug('Finished printing array')


with cv1:
  array = ['o','c','b','a','a','s']
  updated = True
  cv1.notify()
logging.debug('Updated')

with cv2:
  while not finishedProcessing:
    cv2.wait()
  finishedProcessing = False
logging.debug('Finished printing array')

with cv1:
    terminate = True
    cv1.notify()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 template boy