Skip to content

Reduce scope of locks #1668

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

vivekkothari
Copy link
Contributor

@vivekkothari vivekkothari commented Mar 30, 2025

Reduce scope of locks.

RegisterThread is called for every commands and not just watch commands. Thus acquiring a lock before the
if t.Mode == "watch" is wasteful if t.Mode == "command"`, thus reduce the scope of locking.

Also use if else ladder as all three conditions are mutually exclusive.

Summary by CodeRabbit

  • Refactor
    • Streamlined command processing to ensure that user commands are handled efficiently, reducing unnecessary evaluations.
    • Optimized thread management to acquire system resources only when needed, which may enhance overall performance.

Copy link

coderabbitai bot commented Mar 30, 2025

Walkthrough

The changes update command processing in the IOThread’s StartSync method and the locking mechanism in the WatchManager’s RegisterThread method. In IOThread, multiple independent condition checks have been streamlined into an if–else if–else if chain, ensuring that only one branch executes per command. In WatchManager, the mutex is now conditionally acquired only when a thread is in "watch" mode, optimizing the locking behavior without altering public interfaces.

Changes

File(s) Change Summary
internal/server/ironhawk/iothread.go Refactored the StartSync method by replacing separate if statements with an if–else if–else if chain to prioritize HANDSHAKE over WATCH/UNWATCH commands.
internal/server/ironhawk/watch_manager.go Modified the RegisterThread method to acquire a mutex lock conditionally only when the thread's mode is "watch", avoiding unnecessary lock usage.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant I as IOThread
    C->>I: Send command
    alt Command is HANDSHAKE
      I->>I: Process HANDSHAKE (set ClientID & Mode)
    else if Command ends with ".WATCH"
      I->>I: Process WATCH command
    else if Command equals "UNWATCH"
      I->>I: Process UNWATCH command
    end
Loading
sequenceDiagram
    participant T as Thread
    participant WM as WatchManager
    T->>WM: Request registration
    alt Thread mode is "watch"
      WM->>WM: Acquire lock
      WM->>WM: Register thread in watch mode
      WM->>WM: Release lock
    else
      WM->>WM: Register thread without locking
    end
Loading

Poem

Hopping through lines of change with delight,
I see the code now runs ever so light.
Commands flow in structured, graceful rhyme,
And locks appear only when it's time.
A rabbit cheers with hops and ASCII gleam—
Our code evolves like a cherished dream!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2f82354 and 61f8b46.

📒 Files selected for processing (1)
  • internal/server/ironhawk/watch_manager.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/server/ironhawk/watch_manager.go

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f2201d4 and 2f82354.

📒 Files selected for processing (2)
  • internal/server/ironhawk/iothread.go (1 hunks)
  • internal/server/ironhawk/watch_manager.go (1 hunks)
🔇 Additional comments (2)
internal/server/ironhawk/watch_manager.go (1)

37-42: Excellent optimization of lock scope.

This change significantly improves performance by only acquiring the lock when necessary (thread in "watch" mode). Since RegisterThread is called for every command, this optimization reduces contention on the mutex for non-watch commands.

internal/server/ironhawk/iothread.go (1)

61-69: Good refactoring of conditional logic.

Converting separate if statements to an if-else chain clarifies that these conditions are mutually exclusive and improves code readability. This also provides a slight performance improvement by avoiding unnecessary condition checks when the first condition is met.

}

if strings.HasSuffix(c.Cmd, "UNWATCH") {
} else if strings.HasSuffix(c.Cmd, "UNWATCH") {
Copy link

@coderabbitai coderabbitai bot Mar 30, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix the UNWATCH suffix check.

There appears to be a missing dot prefix in the UNWATCH check. This should be ".UNWATCH" to be consistent with the ".WATCH" check and ensure proper command recognition.

-		} else if strings.HasSuffix(c.Cmd, "UNWATCH") {
+		} else if strings.HasSuffix(c.Cmd, ".UNWATCH") {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} else if strings.HasSuffix(c.Cmd, "UNWATCH") {
} else if strings.HasSuffix(c.Cmd, ".UNWATCH") {

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lucifercr07 / @arpitbbhayani Should we do this change?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Comment on lines +134 to +136
// Use RLock instead as we are not really modifying any shared maps here.
w.mu.RLock()
defer w.mu.RUnlock()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change should significantly improve the through put of notifications on watches as RLocks can be acquired concurrently. The earlier code would only allow either one writer or reader to be processed at the same time.

With this change, concurrent users can read but only one writer to be processed.

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