【问题标题】:How can I prevent other threads from running when a certain condition is met?满足特定条件时如何防止其他线程运行?
【发布时间】:2022-08-24 22:27:17
【问题描述】:
我创造了两个线程连续运行的情况。我的目的是在输入 \"printAlphabet\" 函数的 \"Printing Alphabet\" 部分时阻止所有其他线程运行,并且当这个优先线程完成运行时,所有线程恢复执行直到再次满足条件。即使进入此部分,\"anotherThread\" 函数也会继续运行。我知道 Lock 并不是真正的方法,所以如果有人能指出我的解决方案,我将不胜感激。我在一个更大的程序中遇到了同样的情况,并且性能下降非常严重,因为我想要优先考虑的某些操作不允许完成,因为其他线程继续运行。
这是我的代码:
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()
谢谢你的帮助。
标签:
python
python-3.x
multithreading
python-multithreading
【解决方案1】:
尝试使用threading.Events 来暂停其他线程的执行:
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()