我有两个线程,我想让一个线程运行 10 秒,然后让这个线程停止,同时另一个线程执行,然后第一个线程再次启动;重复这个过程。所以例如
from threading import Thread
import sys
import time
class Worker(Thread):
Listened = False;
def __init__(self):
while 1:
if(self.Listened == False):
time.sleep(0)
else:
time.sleep(20)
for x in range(0, 10):
print "I'm working"
self.Listened = True
class Processor(Thread):
Listened = False;
def __init__(self):
# this is where I'm confused!!
Worker().start()
Processer().start()
(P.S. 我已经正确缩进了,但是,SO 似乎有点搞砸了)
基本上,我想要的是:
工作线程工作 10 秒左右,然后停止,“处理器”启动,一旦处理器处理完上次“工作”线程运行的数据,它就会重新启动“ worker ”线程。我不需要特别从当前位置重新启动“ worker ”线程,它可以从头开始。
有人有什么想法吗?
最佳答案
您可以使用 counting semaphore阻塞一个线程,然后唤醒它。
计数信号量是一个具有非负整数计数的对象。如果线程调用 acquire()
在信号量上,当计数为 0 时,thead 将阻塞,直到信号量的计数大于零。要解锁线程,另一个线程必须通过调用 release()
来增加信号量的计数。在信号量上。
创建两个信号量,一个阻塞worker,一个阻塞处理器。将工作信号量的计数从 1 开始,因为我们希望它立即运行。将处理器的信号量计数设置为 0,因为我们希望它阻塞直到 worker 完成。
将信号量传递给工作类和处理器类。 worker 运行 10 秒后,它应该通过调用 processorSemaphore.release()
来唤醒处理器。 , 然后它应该通过调用 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()
关于Python - 是否有可能 "stop"或 "pause"一个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19072608/