Skip to content

Commit 8af4886

Browse files
authored
Make the getNextLoop method multi-thread safe (#274)
1 parent e50b416 commit 8af4886

File tree

2 files changed

+5
-5
lines changed

2 files changed

+5
-5
lines changed

trantor/net/EventLoopThreadPool.cc

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,9 @@ EventLoop *EventLoopThreadPool::getNextLoop()
4747
{
4848
if (loopThreadVector_.size() > 0)
4949
{
50-
EventLoop *loop = loopThreadVector_[loopIndex_]->getLoop();
51-
++loopIndex_;
52-
if (loopIndex_ >= loopThreadVector_.size())
53-
loopIndex_ = 0;
50+
size_t index = loopIndex_.fetch_add(1, std::memory_order_relaxed);
51+
EventLoop *loop =
52+
loopThreadVector_[index % loopThreadVector_.size()]->getLoop();
5453
return loop;
5554
}
5655
return nullptr;

trantor/net/EventLoopThreadPool.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
#include <trantor/exports.h>
1919
#include <vector>
2020
#include <memory>
21+
#include <atomic>
2122

2223
namespace trantor
2324
{
@@ -87,6 +88,6 @@ class TRANTOR_EXPORT EventLoopThreadPool : NonCopyable
8788

8889
private:
8990
std::vector<std::shared_ptr<EventLoopThread>> loopThreadVector_;
90-
size_t loopIndex_;
91+
std::atomic<size_t> loopIndex_{0};
9192
};
9293
} // namespace trantor

0 commit comments

Comments
 (0)