'Terminating Thread Early Based on Another Thread in Python

I have two threads that run in parallel. The checking function checks if an image is on screen and when it appears sleeps for 30 seconds then does various things.

The doing_main_stuff function fetches emails and when a new email arrives performs various tasks.

The code is quite long so I have abbreviated it below.

It works ok but sometimes an email arrives whilst checking is sleeping. In this situation I want to stop the checking function from executing but continue with doing_main_stuff executing.

Once doing_main_stuff has finished I want checking to continue to monitor the screen for the image.

If an email does not arrive during the 30 second sleep then the checking function should execute normally.

Is this possible? I've looked at Event.wait() but this is my first time using threading and am not sure it will do the job.

Here's the abbreviated code:

import datetime, threading, pyautogui as py
from time import sleep

def checking():
    if py.locateOnScreen('rain_check.png'):
        sleep(30)
        print("Check for image then do stuff that takes some time")

def doing_main_stuff():
    print("Fetch emails then do main stuff")
    sleep(1)

while True:

    rc_thread = threading.Thread(target=checking)
    rc_thread.start()

    dms_thread = threading.Thread(target=doing_main_stuff())
    dms_thread.start()


Sources

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

Source: Stack Overflow

Solution Source