在python中运行后台线程

2024-10-01 15:39:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我能得到的所有例子并不能真正解决我的问题,在后台有一个特定的过程不断循环,而程序的其余部分仍在继续。在

下面是一个使用\u 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, ())

忽略了一个显而易见的事实,我们可以跟踪秒数,如果它是10的倍数,那么我该如何更有效地创建它呢。在

在我的实际程序中,线程似乎消耗大量的RAM,我假设是从创建线程的多个实例开始的。我是否必须在每个过程结束时“启动新”线程?在

谢谢你的帮助。在


Tags: import程序newtime过程defsleep线程
2条回答

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

All the examples I've been able to get to don't really address my problem Which examples?

这对我很有用。在

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"

你要求重复一个线程,我不知道你到底需要什么,这可能有用:

^{pr2}$

相关问题 更多 >

    热门问题