Skip to content

fix: resolve thread safety issues in simulation engine#20

Merged
YJack0000 merged 3 commits into
mainfrom
fix/thread-safety
Feb 23, 2026
Merged

fix: resolve thread safety issues in simulation engine#20
YJack0000 merged 3 commits into
mainfrom
fix/thread-safety

Conversation

@YJack0000

Copy link
Copy Markdown
Owner

Summary

  • Make static RNG thread_local in Organism::makeMove() and Genes::defaultMutationLogic() to fix data races
  • Pre-compute organism list once before thread dispatch instead of calling getAllOrganisms() per-thread (was doing N expensive dynamic_pointer_cast scans)
  • Skip std::thread creation overhead when numThreads=1
  • Make handleInteractions single-threaded since it mutates shared state (food->eaten(), organism->killed(), lifeSpan modifications)
  • Keep handleReactions multi-threaded (safe: each thread only writes to its own organism's movement/reactionCounter)
  • Use std::atomic<FoodState> for thread-safe food state transitions
  • Use safe objectsMapper.find() instead of operator[] in threaded context
  • Fix shared_ptr passed by value in calculateDistance (now const ref)
  • Make react()/interact() take const vector references
  • Remove dead removeDeadOrganisms() declaration
  • Remove commented-out debug printf statements

Discussion Points

  • handleInteractions 目前改為 single-threaded 來避免 data race。如果未來需要平行化 interaction phase,可以考慮用 per-object lock 或將 interaction 結果收集後 batch apply
  • Food::canBeEaten()std::atomic<FoodState> 但兩個 organism 仍可能同時看到 FRESH 然後都加 energy。目前這是 acceptable 因為 interaction phase 已改為 single-threaded

Test plan

  • All 3 existing Python tests pass
  • Run benchmark example to verify no performance regression
  • Test with numThreads > 1 to verify reaction phase parallelism still works

🤖 Generated with Claude Code

YJack0000 and others added 3 commits February 24, 2026 03:50
- Make static RNG thread_local in Organism::makeMove() and Genes::defaultMutationLogic()
- Pre-compute organism list once before thread dispatch instead of per-thread
- Skip thread creation overhead when numThreads=1
- Make handleInteractions single-threaded (mutates shared food/organism state)
- Keep handleReactions multi-threaded (only writes to own organism's movement)
- Use std::atomic<FoodState> for thread-safe food state transitions
- Use safe objectsMapper.find() instead of operator[] in threaded context
- Fix shared_ptr passed by value in calculateDistance (now const ref)
- Make react()/interact() take const vector references
- Remove dead removeDeadOrganisms() declaration
- Remove commented-out debug printf statements

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@YJack0000
YJack0000 merged commit 4dd85e1 into main Feb 23, 2026
3 checks passed
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