Optimize EventReactor thread safety with shared_mutex for better concurrency - #1
Merged
Merged
Conversation
Copilot
AI
changed the title
[WIP] 优化 EventReactor 的线程保护机制
Optimize EventReactor thread safety with shared_mutex for better concurrency
Jul 6, 2025
lmshao
approved these changes
Jul 6, 2025
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
The EventReactor class was using
std::mutexfor all operations, creating unnecessary lock contention in high-concurrency scenarios. Read operations likeDispatchEvent()and handler lookups were blocking each other even though they could safely run concurrently.Solution
Replaced the thread protection mechanism from
std::mutextostd::shared_mutexwith read-write lock semantics:Changes Made
Header Updates (
event_reactor.h):#include <shared_mutex>std::mutex mutex_tostd::shared_mutex mutex_Read Operations (use
std::shared_lockfor concurrent access):DispatchEvent()- Multiple threads can now dispatch events concurrentlyRun()method - Handler lookups can happen in parallelModifyHandler()- Only checks handler existence, no modification neededWrite Operations (use
std::unique_lockfor exclusive access):RegisterHandler()- Exclusive access when adding handlersRemoveHandler()- Exclusive access when removing handlersPerformance Benefits
Example Impact
Testing
This optimization is particularly beneficial for high-throughput network applications where multiple events need to be processed concurrently.
💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.