1

我需要知道如何编写一个运行两个线程的程序: 1. 一个线程更新对象的位置(值) 2. 一个线程根据第一个线程的值在其中运行两个方法 所有这些都在一个循环

这是我拥有的当前代码,我想按照我的描述进行更改,而不是值来自 valueList 并且 activate(valueList) 是一个包含几个较小方法的方法。如果您不介意,我很想举个例子来解决这个问题。谢谢

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('59.191.193.42',5555))


screenw = 0
screenh = 0
while 1:
    client_socket.send("loc\n")
    data = client_socket.recv(8192)
    valueList = data.split()

    if (not(valueList[-1] == "eom" and valueList[0] == "start")):
        #print "continuing.."
            continue

        if(screenw != int(valueList[2])):
            screenw = int(valueList[2])
            screenh = int(valueList[3])

    activate(valueList)
4

1 回答 1

3

正如其他人指出的那样,看起来线程实际上并不能解决您的问题。特别是因为 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()
于 2012-09-27T12:53:09.447 回答