我能够做的所有例子都没有真正解决我的问题,在后台不断循环某个程序,而程序的其余部分继续。
以下是使用_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,我假设从创建线程的多个实例。我是否必须在每个程序结束时“start_new”线程?
感谢您的帮助。
答案 0 :(得分:0)
我能够做到的所有例子都没有真正解决我的问题 哪个例子?
这对我有用。
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"
答案 1 :(得分:0)
使用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()