I created a situation in which two threads run continuously. My intention is to prevent all other threads from running when the “Printing Alphabet” portion of the “printAlphabet” function is entered, and when this prioritized thread is done running, all threads resume execution until the condition is met again. The “anotherThread” function continues to run even when this section is entered. I understand that Lock isn’t really the way to go here, so I’d appreciate if someone could point me towards a solution. I have this same situation in a much larger program, and the performance degrades very heavily because certain operations I want to prioritize aren’t allowed to finish because other threads keep running.
Here is my code:
import threading, string, random, time lock = threading.Lock() def anotherThread(): print("Running anotherThread",flush=True) def printAlphabet(): print("Running printAlphabet", flush=True) rand = random.randint(0,1000) print(rand) if rand < 250: with lock: print("Printing Alphabet",flush=True) for letter in string.ascii_lowercase: print(letter, end =" ", flush=True) time.sleep(0.1) def main(): while True: tList = [ threading.Thread(target=anotherThread), threading.Thread(target=printAlphabet), ] for t in tList: t.start() time.sleep(0.5) main()
Thanks for your help.
Advertisement
Answer
Try using threading.Event
s to suspend other threads execution:
import threading, string, random, time def anotherThread(is_printing_alphabet: threading.Event): this_thread = threading.current_thread().name print(f"Running {this_thread}...") i = 0 while i < 10: while not is_printing_alphabet.is_set(): print(f'Processing {i} from {this_thread}...') time.sleep(1) # processing here i += 1 print(f'Running {this_thread}...Done') def printAlphabet(is_printing_alphabet: threading.Event): print("Printing Alphabet! All threads stops!") is_printing_alphabet.set() for letter in string.ascii_lowercase: print(str(letter)) time.sleep(0.01) print('All threads may resume...') is_printing_alphabet.clear() def main(): is_printing_alphabet = threading.Event() threads = [ threading.Thread(target=anotherThread, daemon=True, args=(is_printing_alphabet,)), threading.Thread(target=anotherThread, daemon=True, args=(is_printing_alphabet,)), ] for thread in threads: thread.start() time.sleep(2) print_alphabet = threading.Thread(target=printAlphabet, args=(is_printing_alphabet,)) print_alphabet.start() print_alphabet.join() time.sleep(5) for thread in threads: thread.join() main()