【问题标题】:Simple way to run two while loops at the same time using threading? [closed]使用线程同时运行两个while循环的简单方法? [关闭]
【发布时间】:2013-09-12 20:09:19
【问题描述】:

我已经浏览了所有以前的答案,对于像我这样的初学者来说,它们都太复杂了。我也想同时运行while循环。比如我想同时运行这两个:

def firstFunction():
    do things

def secondFunction():
    do some other things

正如我所说,其他答案太复杂了,我无法理解。

【问题讨论】:

  • 为什么它们太复杂了?你做了什么没成功?
  • 这两个循环有什么作用?功能何时以及如何停止?如果一个在另一个之前停止会发生什么?
  • 你指的while循环在哪里?它们在函数内部吗?
  • 这个 (ibm.com/developerworks/aix/library/au-threadingpython) 是一本我觉得很有帮助的入门书,我的建议是你应该先阅读并理解它。

标签: python python-3.x


【解决方案1】:

假设您的 while 循环在您列出的函数内,这是我能想到的最简单的方法。

from threading import Thread

t1 = Thread(target = firstFunction)
t2 = Thread(target = secondFunction)

t1.start()
t2.start()

正如 tdelaney 所指出的,这样做只会启动每个线程并立即继续。如果您需要在运行程序的其余部分之前等待这些线程完成,您可以使用 .join() 方法。

【讨论】:

  • t1.join()t2.join() 是必需的,以便应用程序等待线程完成。
【解决方案2】:

这是一个非常基本的线程类,可以让您启动并运行。

from threading import *

class FuncThread(threading.Thread):
    def __init__(self, target, *args):
        self._target = target
        self._args = args
        threading.Thread.__init__(self)

    def run(self):
        self._target()

调用它使用:

ThreadOne = FuncThread(firstFunction())
ThreadOne.start()
secondFunction()
ThreadOne.join()

这应该让你非常接近。您将不得不使用它以使其在您的场景中工作。小心运行那些多个while 循环,确保在出口中构建。线程很难,但请尝试在文档中阅读它,并尽可能让我提供的内容为您工作。

http://docs.python.org/2/library/threading.html

【讨论】:

  • FuncThread 不会添加任何超出 threading.Thread 的东西。无需复杂化。
【解决方案3】:

使用thread 模块:

import thread
def firstFunction():
    while some_condition:
       do_something()

def secondFunction():
    while some_other_condition:
       do_something_else()

thread.start_new_thread(firstFunction, ())
thread.start_new_thread(secondFunction, ())

【讨论】:

  • 那些函数是无限循环的呢?
  • @OfirAttia 他们仍然会运行,但永远不会结束。您可能希望线程上的句柄稍后结束它,所以然后使用(在 Python 2.7 中)threading.Thread 类。
猜你喜欢
  • 2023-01-24
  • 1970-01-01
  • 2021-08-24
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
  • 2014-08-03
  • 1970-01-01
  • 2021-09-14
相关资源
最近更新 更多