简体   繁体   English

使用python在两个线程之间等待

[英]Wait in between two threads using python

Need to know whether I can hold a thread for sometime to proceed a action and resume the thread. 需要知道我是否可以保留线程一段时间以继续执行操作并恢复线程。

for example: 例如:

Thread1 having some action to perform and similar like Thread2 is having some action to perform and starting the both threads. 具有执行一些动作的线程1和具有类似于执行线程2的线程的线程1正在执行一些动作并启动两个线程。

if Thread1 fails in Some point I need to pause the Thread2 and proceed the action to perform, If the action says true it should resume the Thread2 and runs the code where it left.. 如果Thread1在某点上失败,则我需要暂停Thread2并继续执行操作,如果该操作为true,则应继续执行Thread2并在其所处位置运行代码。

your answers are welcome!! 欢迎您的回答!

You cannot pause a thread that does not co-operate. 您不能暂停不合作的线程。 You may be able to add some co-operation, though. 不过,您也许可以添加一些合作。 If your thread is a loop, you might be able to emulate a stop signal with a lock: 如果您的线程是一个循环,则可以使用锁模拟停止信号:

foo = threading.Lock()

def thread1():
    while True:
        with foo:
            ... do whatever the thread does...


def thread2():
    while True:
        try:
            do whatevet the thread does
        except MyHorribleException:
            with foo:
                ... do remedial actions with thread1 "paused"...

The caveat of this is that if thread1 holds the lock for a long time, thread2 blocks in exception handling until the lock becomes available. 需要注意的是,如果线程1长时间持有该锁,则线程2会阻塞异常处理,直到该锁可用为止。 Depending on your program logic, this could create a deadlock (thread1 reserving the lock, unable to proceed, waiting for thread2 to fix things but thread2 cannot get the lock as thread1 is holding it). 根据您的程序逻辑,这可能会创建一个死锁(线程1保留锁,无法继续,等待线程2修复问题,但线程2由于线程1持有它而无法获取该锁)。

However, this will guarantee that whenever "remedial actions" are taken, thread1 is not processing data. 但是,这将确保无论何时采取“补救措施”,线程1都不会处理数据。 This might be enough if you have fast processing loops in your threads and thread2 is not needed to fix an ongoing issue with thread1 iteration. 如果您的线程中有快速的处理循环,并且不需要用thread2来解决thread1迭代中的持续性问题,这可能就足够了。

If this is not suitable, then it might be better to use multiprocessing, at least on unix platforms. 如果不合适,那么至少在Unix平台上使用多处理可能会更好。 If you do not create a thread but a subprocess, then you can send it a STOP signal stopping it on its tracks, and when you are ready to proceed, you will send it CONT. 如果您不是创建线程而是子进程,则可以向其发送STOP信号,以使其停止在其轨道上,并且在准备进行操作时,将其发送为CONT。 If you are using Windows, this will probably not work. 如果您使用的是Windows,则可能无法使用。

You might also want to consider redesigning your program logic. 您可能还需要考虑重新设计程序逻辑。 Generally threads are suitable for independent processing. 通常,线程适用于独立处理。 If two threads need to do things in tandem, stopping and continuing each other, it might be better to interleave these threads into one. 如果两个线程需要串联,停止并继续执行,那么最好将这些线程交织在一起。

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

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