Skip to content

fix: thread-safe singleton pattern in MCPManager#822

Open
Jah-yee wants to merge 1 commit intoQwenLM:mainfrom
Jah-yee:fix/thread-safe-singleton
Open

fix: thread-safe singleton pattern in MCPManager#822
Jah-yee wants to merge 1 commit intoQwenLM:mainfrom
Jah-yee:fix/thread-safe-singleton

Conversation

@Jah-yee
Copy link
Copy Markdown

@Jah-yee Jah-yee commented Mar 11, 2026

Description

Fixes issue #812 - Thread unsafe singleton pattern in MCPManager

The MCPManager class uses a singleton pattern that is not thread-safe. In a multi-threaded environment, two threads can simultaneously evaluate cls._instance is None as True, resulting in multiple instances being created.

Solution

Added threading.Lock() to ensure thread-safe singleton creation:

class MCPManager:
    _instance = None
    _lock = threading.Lock()

    def __new__(cls, *args, **kwargs):
        with cls._lock:
            if cls._instance is None:
                cls._instance = super(MCPManager, cls).__new__(cls, *args, **kwargs)
        return cls._instance

This prevents race conditions when multiple threads try to initialize MCPManager concurrently (e.g., when serving multiple users via Gradio WebUI or ASGI servers).

Testing

The fix ensures that only one instance of MCPManager is created even when accessed concurrently from multiple threads.

- Add threading.Lock to prevent race condition in singleton creation
- Multiple threads can now safely initialize MCPManager concurrently
- Fixes issue QwenLM#812
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant