正如其他人指出的那样,看起来线程实际上并不能解决您的问题。特别是因为 Python 代码受制于Global Interpreter Lock,这基本上意味着只有当您的代码受 IO 限制(从磁盘读取大文件、等待慢速网络连接等)时,theading 才会对您有所帮助。如果您的程序是 CPU 密集型的,并且您真的想利用并行处理,那么多处理就是要走的路。使用多处理,您可以用一些内存开销和一点延迟(在创建进程时和进程间通信期间)来换取利用多核 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()