多处理中的Python全局变量

问题描述 投票:0回答:1

对于以下代码,我声明“GlobalCount”,它旨在作为全局变量。 然后我使用多处理启动 process() 方法,每秒递增 GlobalCount。如果我在那里设置断点,该值就会增加。 然后,同时我请求“GETSTATUS”,它应该返回 GlobalCount 的值。然而,它始终是0!我做错了什么?谢谢你。

import multiprocessing
import socket
import time

#globals
GlobalCount = 0

def main():
    global GlobalCount

    server_ip = "127.0.0.1"
    server_port = 2222

    # Create a UDP socket
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server_address = (server_ip, server_port)
    server_socket.bind(server_address)

    print("UDP server is listening on {}:{}".format(*server_address))

    while True:
        
        # Receive data from the client
        data, client_address = server_socket.recvfrom(256)

        if data:

            data_str = data.decode('utf-8') 
            arrayParams = data_str.split(';')

            if arrayParams[0] == "PROCESS":

                server_socket.sendto(response.encode(), client_address)

                # Start the process in parallel
                training_process = multiprocessing.Process(target=process)
                training_process.start()

            elif arrayParams[0] == "GETSTATUS":
                response = str(GlobalCount) #here GlobalCount is always 0
                server_socket.sendto(response.encode(), client_address)

            else:
                print("")



def process():

    global GlobalCount

    for i in range(100):
        
        GlobalCount += 1
        time.sleep(1)


#Execute at start
if __name__ == '__main__':
    main()
python multiprocessing global-variables python-multiprocessing
1个回答
0
投票

在Python中,多处理不会创建线程,而是创建一个具有自己的内存空间的进程

您可以使用 multiprocessing.Value 尝试类似的操作:

from multiprocessing import Value

GlobalCount = Value('i', 0)  # 'i' stands for integer

# In your process function:
def process():
    for i in range(100):
        with GlobalCount.get_lock():  # Ensure thread-safety when updating the value
            GlobalCount.value += 1
        time.sleep(1)

# When reading the value:
current_value = GlobalCount.value
© www.soinside.com 2019 - 2024. All rights reserved.