简体   繁体   English

Python - 是否可以“停止”或“暂停”一个线程

[英]Python - Is it possible to “stop” or “pause” a thread

I have two threads, and, I want one thread to run for 10 seconds, and then have this thread stop, whilst another thread executes and then the first thread starts up again; 我有两个线程,并且,我希望一个线程运行10秒,然后让这个线程停止,而另一个线程执行,然后第一个线程再次启动; this process is repeated. 这个过程重复进行。 So eg 所以,例如

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()

(PS I have indented correctly, however, SO seems to have messed it up a bit) (PS我已正确缩进,但是,似乎有点搞砸了)

Basically, what I want is: 基本上,我想要的是:

The worker thread works for 10 seconds (or so) and then stops, the "processor" starts up and, once the processor has processed the data from the last run of the "Worker" thread, it then re-starts the "worker" thread up. 工作线程工作10秒钟(或左右)然后停止,“处理器”启动,一旦处理器处理了“工作”线程的最后一次运行的数据,它就重新启动“工人”搞砸了。 I don't specifically have to re-start the "worker" thread from that current position, it can start from the beginning. 我没有必要从当前位置重新启动“worker”线程,它可以从头开始。

Does anyone have any ideas? 有没有人有任何想法?

You can use a counting semaphore to block a thread, and then wake-it-up later. 您可以使用计数信号量来阻塞线程,然后稍后将其唤醒。

A counting semaphore is an object that has a non-negative integer count. 计数信号量是具有非负整数计数的对象。 If a thread calls acquire() on the semaphore when the count is 0, the thead will block until the semaphore's count becomes greater than zero. 如果一个线程在计数为0时调用信号量上的acquire() ,则该块将阻塞,直到信号量的计数变为大于零。 To unblock the thread, another thread must increase the count of the semaphore by calling release() on the semaphore. 要解除阻塞线程,另一个线程必须通过调用信号量上的release()来增加信号量的计数。

Create two semaphores, one to block the worker, and one to block the processor. 创建两个信号量,一个用于阻止工作,另一个用于阻止处理器。 Start the worker semaphore's count a 1 since we want it to run right away. 因为我们希望它立即运行,所以启动工人信号量的计数为1。 Start the processor's semaphore's count to 0 since we want it to block until the worker is done. 将处理器的信号量计数设置为0,因为我们希望它在工作完成之前阻塞。

Pass the semaphores to the worker and processor classes. 将信号量传递给worker和processor类。 After the worker has run for 10 seconds, it should wake-up the processor by calling processorSemaphore.release() , then it should sleep on its semaphore by calling workerSemaphore.acquire() . 在worker运行10秒后,它应该通过调用processorSemaphore.release()唤醒processorSemaphore.release() ,然后它应该通过调用workerSemaphore.acquire()在其信号量上休眠。 The processor does the same. 处理器也是如此。

#!/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()

See Alvaro's answer. 见阿尔瓦罗的回答。 But if you must really use threads then you can do something like below. 但如果你必须真正使用线程,那么你可以做类似下面的事情。 However you can call start() on a Thread object only once. 但是,您只能在Thread对象上调用start()一次。 So either your data should preserve state as to where the next Worker thread should start from and you create a new worker thread in Processor every time or try to use a critical section so that the Worker and Processor threads can take turns to access it. 因此,您的数据应该保留关于下一个Worker线程应该从哪里开始的状态,并且每次在Processor创建一个新的工作线程,或者尝试使用临界区,以便Worker线程和Processor线程轮流访问它。

#!/usr/bin/env python
from threading import Thread 
import time

class Worker(Thread):

    def __init__(self):
        Thread.__init__(self)
        pass

    def run(self):
        for x in range(0, 10):
            print "I'm working"
            time.sleep(1)

class Processor(Thread):

    def __init__(self, w):
        Thread.__init__(self)
        self.worker = w

    def run(self):
            # process data from worker thread, add your logic here
            self.worker.start()

w = Worker()    
p = Processor(w)
p.start()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM