您可以使用计数信号量来阻塞线程,然后稍后将其唤醒。
计数信号量是具有非负整数计数的对象。如果一个线程acquire()
在计数为 0 时调用信号量,则 thead 将阻塞,直到信号量的计数大于零。要解除对线程的阻塞,另一个线程必须通过调用信号量来增加信号量的计数release()
。
创建两个信号量,一个用于阻塞工作线程,一个用于阻塞处理器。启动工作信号量的计数为 1,因为我们希望它立即运行。将处理器的信号量计数设为 0,因为我们希望它阻塞,直到 worker 完成。
将信号量传递给工作者和处理器类。worker 运行 10 秒后,它应该调用 唤醒处理器processorSemaphore.release()
,然后调用 semaphore 在其信号量上休眠workerSemaphore.acquire()
。处理器也是如此。
#!/usr/bin/env python
from threading import Thread, Semaphore
import sys
import time
INTERVAL = 10
class Worker(Thread):
def __init__(self, workerSemaphore, processorSemaphore):
super(Worker, self).__init__()
self.workerSemaphore = workerSemaphore
self.processorSemaphore = processorSemaphore
def run(self):
while True:
# wait for the processor to finish
self.workerSemaphore.acquire()
start = time.time()
while True:
if time.time() - start > INTERVAL:
# wake-up the processor
self.processorSemaphore.release()
break
# do work here
print "I'm working"
class Processor(Thread):
def __init__(self, workerSemaphore, processorSemaphore):
super(Processor, self).__init__()
print "init P"
self.workerSemaphore = workerSemaphore
self.processorSemaphore = processorSemaphore
def run(self):
print "running P"
while True:
# wait for the worker to finish
self.processorSemaphore.acquire()
start = time.time()
while True:
if time.time() - start > INTERVAL:
# wake-up the worker
self.workerSemaphore.release()
break
# do processing here
print "I'm processing"
workerSemaphore = Semaphore(1)
processorSemaphore = Semaphore(0)
worker = Worker(workerSemaphore, processorSemaphore)
processor = Processor(workerSemaphore, processorSemaphore)
worker.start()
processor.start()
worker.join()
processor.join()