You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python多进程全局变量共享问题修复及循环条件逻辑实现求助

Fixing Cross-Process Variable Sharing & Loop Logic in Python Multiprocessing

Hey there! Let's tackle your two core issues one by one—first, why your global variable isn't updating across processes, then how to implement the looping logic in test2.

Why Your Global Variable Isn't Working

The key thing to remember about Python's multiprocessing is that each process gets its own copy of the memory space from the parent process. When you modify a in test1, you're only changing the copy of a that lives inside the t1 process—not the one in the main process or the t2 process. That's why test2 still prints the original "Wait" value.

Solution 1: Using Shared Memory Objects

To share data across processes, you need to use multiprocessing's built-in shared memory tools. The easiest approach here is to use Manager().Value (for single values) since we're dealing with a string.

Solution 2: Implementing the Loop in test2

For test2, we'll add a loop that checks the shared variable repeatedly. We'll add a small time.sleep() inside the loop to avoid hogging CPU resources.

Modified Working Code

import time
import multiprocessing
from multiprocessing import Manager

def test1(shared_a):
    print("\n#######################\nFunction 1")
    time.sleep(1)
    # Update the shared variable
    shared_a.value = "Loaded Data"
    print(f"Updated shared value: {shared_a.value}")

def test2(shared_a):
    print("\n#######################\nFunction 2")
    # Loop until the shared variable matches our target value
    while shared_a.value != "Loaded Data":
        print("Loading Data …. Please Wait")
        time.sleep(0.5)  # Prevent excessive CPU usage
    print(f"Done! Value is now: {shared_a.value}")

if __name__ == '__main__':
    # Create a manager to handle shared variables
    with Manager() as manager:
        # Create a shared string variable initialized to "Wait"
        shared_a = manager.Value('c', "Wait")
        # Start both processes at the same time
        t1 = multiprocessing.Process(target=test1, args=(shared_a,))
        t2 = multiprocessing.Process(target=test2, args=(shared_a,))
        
        t1.start()
        t2.start()
        
        # Wait for both processes to finish
        t1.join()
        t2.join()

Key Changes Explained

  • Shared Variable: We use Manager().Value('c', "Wait") where 'c' indicates we're storing a string. This variable lives in a separate server process that all child processes can access and modify.
  • No Global Variables: Instead of relying on global variables, we pass the shared variable as an argument to both functions—this makes the code clearer and avoids confusion with process-specific copies.
  • Loop in test2: The loop runs as long as shared_a.value isn't "Loaded Data", printing the waiting message every 0.5 seconds. Once test1 updates the shared value, the loop exits automatically.
  • Simultaneous Start: We start both processes right after each other (no unnecessary sleep(2)), so test2 begins waiting immediately instead of being delayed.

Expected Output

#######################
Function 2
Loading Data …. Please Wait
Loading Data …. Please Wait

#######################
Function 1
Updated shared value: Loaded Data
Done! Value is now: Loaded Data

内容的提问来源于stack exchange,提问作者Hammad Rafique

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 11:37:38