我需要制作 3 个线程来打印信号量颜色:按此顺序红色、黄色和绿色,然后,每个踏板必须随机休眠 N 秒。每种颜色必须为一个线程打印,所有这个过程必须重复 N 次。
我试过将 lock.acquire() 和 lock.release() 移出 for 循环,但不起作用 =(
from termcolor import colored
import threading
import time
from random import randrange
def threadRed(n, lock, tempo):
for i in range(n):
lock.acquire()
print(colored("red", 'grey', 'on_red', attrs=['dark', 'bold']))
print(colored("I'm going to sleep for %d seconds," % tempo, 'red'))
time.sleep(tempo)
lock.release()
def threadYellow(n, lock, tempo):
for i in range(n):
lock.acquire()
print(colored("yellow", 'grey', 'on_yellow', attrs=['dark', 'bold']))
print(colored("I'm going to sleep for %d seconds," % tempo, 'yellow'))
time.sleep(tempo)
lock.release()
def threadGreen(n, lock, tempo):
for i in range(n):
lock.acquire()
print(colored("green", 'grey', 'on_green', attrs=['dark', 'bold']))
print(colored("I'm going to sleep for %d seconds," % tempo, 'green'))
time.sleep(tempo)
lock.release()
lock = threading.Lock()
repeticoes = 5
tempo = randrange(1, 11)
t_red = threading.Thread(target=threadRed, args=(repeticoes, lock, tempo))
tempo = randrange(1, 11)
t_yellow = threading.Thread(target=threadYellow, args=(repeticoes, lock, tempo))
tempo = randrange(1, 11)
t_green = threading.Thread(target=threadGreen, args=(repeticoes, lock, tempo))
t_red.start()
t_yellow.start()
t_green.start()
t_red.join()
t_yellow.join()
t_green.join()
简而言之,我的代码正在打印:
但我需要这是显示的结果:
catspeake
慕莱坞森
相关分类