正如其他人所指出的那樣,它看起來並不像線程實際上是要解決你的問題。特別是因爲Python代碼受限於Global Interpreter Lock,這基本上意味着如果您的代碼是IO-綁定的(從磁盤讀取大文件,等待慢速網絡連接等),則只會幫助您執行代碼。如果您的程序受CPU限制,並且您確實想要利用並行處理,則需要使用multiprocessing。通過多處理,您可以交換一些內存開銷和一點延遲(在進程創建時以及進程間通信期間),以便利用多核CPU。
就在平行處理確實對你的程序有用,或者你只是好奇而已,我提出下面的代碼示例。免責聲明,我沒有試過導入這個模塊,所以認爲它是僞代碼。
import socket
from multiprocessing import Process, Queue, Value
from ctypes import c_bool
HOST = '198.51.100.0'
PORT = 8080
# This function will be run in a child process
def update_proc(data_queue, update_queue, quit_flag):
while not quit_flag.value:
data = data_queue.get()
# do something with the data...
update_queue.put(data)
print "Closing child update process"
# This function will be run in a child process
def activate_proc(update_queue, quit_flag):
while not quit_flag.value:
data = update_queue.get()
# do something with the data...
print "Closing child activate process"
# main process begins execution here, if module is run from the terminal
if __name__ == "__main__":
# Connect to remote host over TCP
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST,PORT))
# Set up a Queue to pass data to the update process, and another one
# for the two children to communicate
data_queue = Queue()
update_queue = Queue()
# The quit_flag Value is a *very* primitive way to signal the child
# processes to quit. I'm sure there are better ways to do this, but I'm
# tired and can't think of any right now.
quit_flag = Value(c_bool, False)
# Create two child processes, pass a reference to the Queue to each
update = Process(target=update_proc, args=(data_queue, update_queue, quit_flag))
activate = Process(target=activate_proc, args=(update_queue, quit_flag))
update.start()
activate.start()
# Read data from the TCP socket, push it onto the data_queue
while True:
client.sendall("loc\n")
data = client.recv(8192)
if not data:
print "network connection closed by client"
break
data_queue.put(data)
# Join with child processes before closing
print "All done, closing child processes"
update.join()
activate.join()
目前尚不清楚爲什麼您希望它是多線程的。你期望'激活'需要很長時間嗎?如果是這樣,當處理先前收到的valueList時,你想要發生什麼,當下一個到達時,它仍然在進行中? –
只有在絕對必要時才使用多線程 - 您爲一個看似簡單的問題增加了很多複雜性。 – hochl
@TimoKluck比較值。因爲actiavte(valueList)方法包含兩個方法,它們根據valueList的更改來移動機器人。我對當前代碼的問題是,值傳遞得太快,以至於我的機器人重複相同的動作一段時間 – Edward