我正试图弄清楚如何在一个有工作线程池的函数中实现一个只打印一次的print语句。因此,如果有两个线程在池中运行,我只需要一个线程来打印它。我正试图通过使用计数器来实现这一点,我一直在处理多个线程。值,这样它会增加权利,但我现在删除了它。每当计数器达到5时,它就会从计数器中减去5并打印一些东西。
from multiprocessing import Pool, Value, Lock
from colorama import Fore
counter = 0
def check(line):
counter+=1
if counter == 5:
counter-=5
print(Fore.YELLOW + "Counter Reached 5")
else:
pass
#my other code here that normally gets executed
def main():
#args.threads is taken from an argument given by the user before program starts
pool = Pool(args.threads)
pool.daemon = True
results = pool.map(check, arrange)
当然,它们是更多的代码,但这正是我需要帮助的地方。当计数器达到5时,我希望只打印一个线程,而不是池中的所有线程。
这里有一个接近上面内容的快速示例。。。
import time
import multiprocessing as mp
from multiprocessing import Pool, Value, Lock
counter = Value('i',0) # integer value starting at 0
lock = Lock()
def check(line):
with lock:
counter.value += 1
if counter.value == 5:
with lock:
counter.value -= 5
print('Counter Reached 5 in process ', mp.current_process() )
return 1
else:
time.sleep(0.1)
return 0
pool = Pool(processes=4)
results = pool.map(check, range(15))
print(results)
这给出了(注意,首先到达"5"的过程是随机的(。。
Counter Reached 5 in process <ForkProcess(ForkPoolWorker-1, started daemon)>
Counter Reached 5 in process <ForkProcess(ForkPoolWorker-2, started daemon)>
Counter Reached 5 in process <ForkProcess(ForkPoolWorker-1, started daemon)>
[0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]
Lock()
将在修改Value
时防止潜在的竞争问题。如果删除with lock:
行并多次运行上面的代码,由于竞争条件,您将看到它只间歇性地打印两次。这里对Lock
进行了很好的讨论。