gpt4 book ai didi

python - 在循环中运行两个相互依赖的线程

转载 作者:行者123 更新时间:2023-11-30 23:40:30 26 4
gpt4 key购买 nike

我需要知道如何编写运行两个线程的程序: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)

最佳答案

正如其他人指出的那样,线程实际上并不能解决您的问题。特别是因为 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()

关于python - 在循环中运行两个相互依赖的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12620748/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com