Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Jul 28, 2025

This PR implements a configurable sleep mechanism for the global() method when accessing singleton instances that are not yet initialized, addressing race conditions in multi-threaded scenarios.

Changes Made

Core Implementation

  • Enhanced macro parameters: Added sleep_ms parameter to configure sleep duration (default: 500ms)
  • Sleep/retry logic: Instead of panicking immediately when singleton is not initialized, the global() method now:
    • Sleeps for the configured duration
    • Retries up to 20 times (configurable in generated code)
    • Eventually panics with detailed error message if initialization never completes

New Usage Patterns

// Default 500ms sleep
#[singleton]
struct Config { /* ... */ }

// Custom sleep duration
#[singleton(sleep_ms = 1000)]
struct Settings { /* ... */ }

// Arc mode with custom sleep
#[singleton(arc, sleep_ms = 300)]
struct Database { /* ... */ }

Multi-threaded Benefits

Before this change, accessing an uninitialized singleton would panic immediately:

// Thread 1: tries to access singleton
let config = Config::global(); // ❌ Immediate panic

// Thread 2: initializes singleton (too late)
Config::init(Config { /* ... */ });

Now, Thread 1 will sleep and wait for Thread 2 to complete initialization:

// Thread 1: tries to access singleton
let config = Config::global(); // ✅ Sleeps 500ms, retries, succeeds

// Thread 2: initializes singleton
Config::init(Config { /* ... */ }); // Completes during retry period

Backward Compatibility

All existing code continues to work without changes. The sleep mechanism is enabled by default with sensible defaults (500ms intervals, 20 max retries = 10 second timeout).

Documentation & Testing

  • Updated README with comprehensive examples and API documentation
  • Added unit tests covering sleep functionality, timeout behavior, and parameter parsing
  • Included practical examples demonstrating multi-threaded usage patterns
  • All existing tests continue to pass

Fixes #3.


💬 Share your feedback on Copilot coding agent for the chance to win a $200 gift card! Click here to start the survey.

@qyuzh qyuzh changed the title [WIP] feat: [WIP] feat: sleep when cannot get instance Jul 28, 2025
Co-authored-by: qyuzh <40571736+qyuzh@users.noreply.github.com>
Copilot AI changed the title [WIP] feat: sleep when cannot get instance feat: Add configurable sleep mechanism for singleton global() method Jul 28, 2025
Copilot AI requested a review from qyuzh July 28, 2025 05:43
Copilot finished work on behalf of qyuzh July 28, 2025 05:43
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.

feat: sleep when cannot get instance

2 participants