在Python中运行后台线程

4

我能够提供的所有示例都没有真正解决我的问题,即在后台不断循环执行某个过程,而程序的其余部分继续运行。

以下是一个使用_thread方法的简单示例:

import _thread
import time


def countSeconds():
    time.sleep(1)
    print("Second")
    _thread.start_new(countSeconds, ())

def countTenSeconds():
    time.sleep(10)
    print("Ten seconds passed")
    _thread.start_new(countTenSeconds, ())


_thread.start_new(countSeconds, ())
_thread.start_new(countTenSeconds, ())

忽略我们可以追踪秒数的明显事实,如果它是十的倍数,则打印不同的东西,我该如何更有效地创建这个程序。

在我的实际程序中,线程似乎在消耗内存,我假设是由于创建多个线程实例而导致的。我需要在每个过程的结尾处“start_new”线程吗?

感谢任何帮助。


重新调用自身的线程似乎并不太合理,也许你需要类似这样的东西:https://dev59.com/zGcs5IYBdhLWcg3w-Yr4 - Philip Feldmann
你为什么不使用 threading 模块呢?它比使用低级别的 _thread 模块更简单。此外,由于 GIL,Python 线程应用程序实际上并不是并行的 - 你需要使用 multiprocessing 来实现并行。 - skrrgwasme
我同意@skrrgwasme的观点。我会使用线程(或者异步编程)。此外,这正是线程的整个目标(在单个进程中同时运行多个线程[任务])。 - undefined
2个回答

6

我找到的所有示例都没有真正解决我的问题 都有哪些示例呢?

这对我有效。

import threading

def f():
    import time
    time.sleep(1)
    print "Function out!"

t1 = threading.Thread(target=f)

print "Starting thread"
t1.start()
time.sleep(0.1)
print "Something done"
t1.join()
print "Thread Done"

您正在寻求一个重复的线程,我不太明白您需要什么,这可能会有所帮助:
import threading
var = False
def f():
    import time
    counter = 0
    while var:
        time.sleep(0.1)
        print "Function {} run!".format(counter)
        counter+=1

t1 = threading.Thread(target=f)

print "Starting thread"
var = True
t1.start()
time.sleep(3)
print "Something done"
var = False
t1.join()
print "Thread Done"

这个例子的问题在于它不是递归的。它只运行一次函数,然后退出。 - Constantly Confused

3

使用 threading.timer 来继续启动新的后台线程。

import threading
import time


def countSeconds():
    print("Second")
    threading.Timer(1, countSeconds).start()

def countTenSeconds():
    print("Ten seconds passed")
    threading.Timer(10, countTenSeconds).start()


threading.Timer(1, countSeconds).start()
threading.Timer(10, countTenSeconds).start()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接