在 python 中运行后台线程

Con*_*sed 5 python multithreading

我所能得到的所有示例都没有真正解决我的问题,即后台中的某个程序不断循环,而程序的其余部分仍在继续。

下面是一个使用 _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, ())
Run Code Online (Sandbox Code Playgroud)

忽略一个明显的事实,即我们可以跟踪秒数,并且如果它是十的倍数,则只打印不同的内容,我将如何更有效地创建它。

在我的实际程序中,线程似乎会消耗大量内存,我假设是通过创建线程的多个实例来实现的。我是否必须在每个过程结束时“start_new”线程?

谢谢你的帮助。

tgl*_*ria 6

我所能得到的所有例子并没有真正解决我的问题哪些例子?

这对我有用。

import threading
import time

def f():
    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"
Run Code Online (Sandbox Code Playgroud)

您要求重复线程,我不明白您到底需要什么,这可能有效:

import threading
import time

var = False
def f():
    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"
Run Code Online (Sandbox Code Playgroud)