簡體   English   中英

在python中運行后台線程

[英]Running a background thread in python

我已經獲得的所有示例並沒有真正解決我的問題,即在后台有某個過程不斷循環,而程序的其余部分仍在繼續。

這是使用_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的倍數就可以打印出不同的東西,我將如何更有效地創建它。

在我的實際程序中,我假設從創建線程的多個實例開始,線程似乎在消耗大量內存。 在每個過程的末尾是否都必須有“ start_new”線程?

謝謝你的幫助。

我能夠獲得的所有示例並沒有真正解決我的問題哪些示例?

這確實對我有用。

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"

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM