0

I am learning how to use multithreading in python, I have 2 functions which runs at the same time(one replays some inputs enter with the mouse and the keyboard, the second one records the process) I want the second function to record just until there are no more inputs to enter, so I declared a global variable to false and change it to true once there is no more inputs, but the while loop does not seem to take the change of the variable. This is my code:

STOP_RECORDING = False
file = "actions_test_10-07-2020_15-56-43.json"

def main():
    t1 = threading.Thread(target=playActions, args=[file])
    t2 = threading.Thread(target=recordScreen)

    t1.start()
    t2.start()

    t1.join()
    t2.join()

    print("Done")

def recordScreen():
    output = "video.avi"
    img = pyautogui.screenshot()
    img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
    # get info from img
    height, width, channels = img.shape
    # Define the codec and create VideoWriter object
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    out = cv2.VideoWriter(output, fourcc, 30.0, (width, height))

    while not STOP_RECORDING:
        try:
            img = pyautogui.screenshot()
            image = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
            out.write(image)
            StopIteration(0.5)
        except KeyboardInterrupt:
            break

    out.release()
    cv2.destroyAllWindows()

def playActions(filename):
    # basically repeats some inputs recorded before
 
    STOP_RECORDING = True

Jesus Fernandez
  • 500
  • 1
  • 7
  • 20
  • Probably the most common way of doing it is using a thread safe object like a `Queue` and transfer data that way. Check [this](https://stackoverflow.com/a/25904681/10039400) for example – DJSchaffner Oct 07 '20 at 15:19
  • i agree on DJSchaffner, but you should also read [this](https://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python) and [this](https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces) about Scopes and Namespaces – NWiogrhkt Oct 07 '20 at 15:37
  • thanks to both of you I got to understand much better how it works and the code is working now – Jesus Fernandez Oct 08 '20 at 14:48

0 Answers0